Create a new file called with the following content and give it executable permissions with 

chmod +x 

Execute/Run via: 


#!/usr/bin/env bash
# Note that spaces cannot be used around the `=` assignment operator whom_variable="World"
# Use printf to safely output the data
printf "Hello, %s\n" "$whom_variable"

#> Hello, World

This will print Hello, World to standard output when executed.
To tell bash where the script is you need to be very specific, by pointing it to the containing directory, normally with ./ if it is your working directory, where . is an alias to the current directory. If you do not specify the directory, bash tries to locate the script in one of the directories contained in the $PATH environment variable.

The following code accepts an argument $1 , which is the first command line argument, and outputs it in a formatted string, following Hello, .
Execute/Run via: 

./ World
#!/usr/bin/env bash
printf "Hello, %s\n" "$1"

#> Hello, World
It is important to note that $1 has to be quoted in double quote, not single quote. "$1" expands to the first command line argument, as desired, while '$1' evaluates to literal string $1 .

Hello World with User Input

The following will prompt a user for input, and then store that input as a string (text) in a variable. The variable is then used to give a message to the user.

#!/usr/bin/env bashecho "Who are you?"read nameecho "Hello, $name."

The command read here reads one line of data from standard input into the variable name . This is then referenced using $name and printed to standard out using echo .
Example output:

$ ./hello_world.shWho are you?MattHello, Matt.

Here the user entered the name "Matt", and this code was used to say Hello, Matt. .
And if you want to append something to the variable value while printing it, use curly brackets around the variable name as shown in the following example:

#!/usr/bin/env bashecho "What are you doing?"read actionecho "You are ${action}ing."

Example output:$ ./hello_world.shWhat are you doing?SleepYou are Sleeping.

Here when user enters an action, "ing" is appended to that action while printing.

Importance of Quoting in Strings

Quoting is important for string expansion in bash. With these, you can control how the bash parses and expands your strings.
There are two types of quoting:

1. Weak: uses double quotes: "

2. Strong: uses single quotes: '

If you want to bash to expand your argument, you can use Weak Quoting:

#!/usr/bin/env bashworld="World"echo "Hello $world"#> Hello World

If you don't want to bash to expand your argument, you can use Strong Quoting:

#!/usr/bin/env bashworld="World"echo 'Hello $world'#> Hello $world

You can also use escape to prevent expansion:

#!/usr/bin/env bashworld="World"echo "Hello \$world"#> Hello $world

Peace out


Post a Comment

Post a Comment (0)

Previous Post Next Post