What is echo $1 in Bash

Echo $1 Bash

Meaning of the echo $1 in Bash

The echo $1 is a bash command; now, those new to Bash can think of it as a famous shell and scripting language in Unix-based operating systems. Using Bash, we can take advantage of multiple features and commands that assist users in automation and system administration tasks.

Are you comfortable with Bash? Great, let’s continue with echo $1. First, the echo command displays messages and outcomes on the console. For instance, if we want to show Hi, we will use echo "Hi" and hit Enter.

This way, Hi will be printed on the console. Now, what does $1 means? In Bash, $1 represents the first argument passed to the function or a bash script. So, if you have multiple arguments to pass, then $1 will mean the first argument, $2 will represent the second argument, and so on.

Combining echo and $1 as echo $1 means printing or displaying the first argument’s value passed to the particular function or a script. Let’s understand the use of echo $1 with a script and function.

Use if-else in Bash Script to Demonstrate echo $1

Use if-else in Bash Script to Demonstrate the use of the echo $1 command.

The output will differ based on the given arguments or no arguments. Let’s run the above file as ./test.sh 9 to get an outcome.

In the provided script above, we used if-else blocks to check the first argument’s value, whether it is a positive number, negative number, zero, or not provided. Here, we used various expressions and operators to check the value of the $1.

First, the -z option was used to check if the variable was empty, so [-z "$1"] was used to check if the first command line argument was an empty string. Next, [ $1 -gt 0 ] was used to check if the value of the first command-line argument was greater than 0. Here, -gt is a comparison operator meaning greater than.

Finally, [ $1 -lt 0 ] was used to check if the value of the first command-line argument is less than 0. Here, -lt is a comparison operator meaning less than.

Only one block will be executed at a time, whether it is if, elif or else.

Use User-Defined Function to Demonstrate echo $1

Use user-defined functions using the console to learn how to use echo $1 in Bash.

Here, we defined a function named printFirstArgument to whom we passed Hello, how are you? as the first command-line argument, which was printed due to using echo $1 as you can inside the function body. You can also write this function in a bash script and run that script by passing the same argument.

That’s all about echo $1 in Bash.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *