乐闻世界logo
搜索文章和话题

How to use conditional in bash script to check string argument

1个答案

1

Implementing conditional checks for string parameters in Bash scripts is a common practice, primarily used to execute different operations based on varying input parameters. This enhances the flexibility and functionality of the script.

Example Scenario

For instance, consider writing a script that evaluates the user's input name and outputs a corresponding welcome or warning message.

Script Content

Here is a simple example script welcome.sh:

bash
#!/bin/bash # Get the user's input name name=$1 # Verify that a name is provided if [ -z "$name" ]; then echo "Error: No name provided." exit 1 fi # Conditional check: if the input is 'Alice', print a specific welcome message if [ "$name" == "Alice" ]; then echo "Welcome back, Alice!" # Otherwise, print a general welcome message else echo "Hello, $name!" fi

Detailed Explanation

  1. Parameter Retrieval:

    • name=$1: This assigns the first script argument to the variable name.
  2. Parameter Validation:

    • if [ -z "$name" ]: This uses -z to check if $name is empty. If empty, it outputs an error message and exits.
  3. String Comparison:

    • if [ "$name" == "Alice" ]: This checks if the input name is "Alice". If true, it prints a specific welcome message.

Executing the Script

To run this script, enter the following command in the terminal:

bash
chmod +x welcome.sh ./welcome.sh Alice

The output will be:

shell
Welcome back, Alice!

If you input another name:

bash
./welcome.sh Bob

The output will be:

shell
Hello, Bob!

This example demonstrates that by using conditional statements in Bash scripts to check string parameters, we can execute different code logic based on input, making the script more flexible and useful.

2024年6月29日 12:07 回复

你的答案