Write a script that prints “hello, world”, followed by a new line to the standard output.

Example

Interactive Shell

The Bash shell is commonly used interactively: It lets you enter and edit commands, then executes them when you press the Return key. Many Unix-based and Unix-like operating systems use Bash as their default shell [notably Linux and macOS]. The terminal automatically enters an interactive Bash shell process on startup.

Output Hello World by typing the following:

echo "Hello World"
#> Hello World  # Output Example

Notes

  • You can change the shell by just typing the name of the shell in terminal. For example: sh, bash, etc.

  • echo is a Bash builtin command that writes the arguments it receives to the standard output. It appends a newline to the output, by default.

Non-Interactive Shell

The Bash shell can also be run non-interactively from a script, making the shell require no human interaction. Interactive behavior and scripted behavior should be identical – an important design consideration of Unix V7 Bourne shell and transitively Bash. Therefore anything that can be done at the command line can be put in a script file for reuse.

Follow these steps to create a Hello World script:

  1. Create a new file called hello-world.sh

    touch hello-world.sh
    
  2. Make the script executable by running chmod+x hello-world.sh

  3. Add this code:

    #!/bin/bash
    echo "Hello World"
    

    Line 1: The first line of the script must start with the character sequence #!, referred to as shebang1. The shebang instructs the operating system to run /bin/bash, the Bash shell, passing it the script's path as an argument.

    E.g. /bin/bash hello-world.sh

    Line 2: Uses the echo command to write Hello World to the standard output.

  1. Execute the hello-world.sh script from the command line using one of the following:

    • ./hello-world.sh – most commonly used, and recommended
    • /bin/bash hello-world.sh
    • bash hello-world.sh – assuming /bin is in your $PATH
    • sh hello-world.sh

For real production use, you would omit the .sh extension [which is misleading anyway, since this is a Bash script, not a sh script] and perhaps move the file to a directory within your PATH so that it is available to you regardless of your current working directory, just like a system command such as cat or ls.

Common mistakes include:

  1. Forgetting to apply execute permission on the file, i.e., chmod +x hello-world.sh, resulting in the output of ./hello-world.sh: Permission denied.

  2. Editing the script on Windows, which produces incorrect line ending characters that Bash cannot handle.

    A common symptom is : command not found where the carriage return has forced the cursor to the beginning of line, overwriting the text before the colon in the error message.

    The script can be fixed using the dos2unix program.

    An example use: dos2unix hello-world.sh

    dos2unix edits the file inline.

  3. Using sh ./hello-world.sh, not realizing that bash and sh are distinct shells with distinct features [though since Bash is backwards-compatible, the opposite mistake is harmless].

    Anyway, simply relying on the script's shebang line is vastly preferable to explicitly writing bash or sh [or python or perl or awk or ruby or...] before each script's file name.

    A common shebang line to use in order to make your script more portable is to use #!/usr/bin/env bash instead of hard-coding a path to Bash. That way, /usr/bin/env has to exist, but beyond that point, bash just needs to be on your PATH. On many systems, /bin/bash doesn't exist, and you should use /usr/local/bin/bash or some other absolute path; this change avoids having to figure out the details of that.

1 Also referred to as sha-bang, hashbang, pound-bang, hash-pling.




This section presents several shell script examples.

Hello World

Example 9. Hello World

#!/bin/sh
echo "Hello world"

Using Arguments

Example 10. Shell Script Arguments

#!/bin/bash

# example of using arguments to a script
echo "My first name is $1"
echo "My surname is $2"
echo "Total number of arguments is $#" 

Save this file as name.sh, set execute permission on that file by typing chmod a+x name.sh and then execute the file like this: ./name.sh.

$ chmod a+x name.sh
$ ./name.sh Hans-Wolfgang Loidl
My first name is Hans-Wolfgang
My surname is Loidl
Total number of arguments is 2

Version 1: Line count example

The first example simply counts the number of lines in an input file. It does so by iterating over all lines of a file using a while loop, performing a read operation in the loop header. While there is a line to process, the loop body will be executed in this case simply increasing a counter by [[counter++]]. Additionally the current line is written into a file, whose name is specified by the variable file, by echoing the value of the variable line and redirecting the standard output of the variable to $file. the current line to file. The latter is not needed for the line count, of course, but demonstrates how to check for success of an operation: the special variable $? will contain the return code from the previous command [the redirected echo]. By Unix convention, success is indicated by a return code of 0, all other values are error code with application specific meaning.

Another important issue to consider is that the integer variable, over which iteration is performed should always count down so that the analysis can find a bound. This might require some restructuring of the code, as in the following example, where an explicit counter z is introduced for this purpose. After the loop, the line count and the contents of the last line are printed, using echo. Of course, there is a Linux command that already implements line-count functionality: wc [for word-count] prints, when called with option -l, the number of lines in the file. We use this to check wether our line count is correct, demonstrating numeric operations on the way.

#!/bin/bash
# Simple line count example, using bash
#
# Bash tutorial: //linuxconfig.org/Bash_scripting_Tutorial#8-2-read-file-into-bash-array
# My scripting link: //www.macs.hw.ac.uk/~hwloidl/docs/index.html#scripting
#
# Usage: ./line_count.sh file
# -----------------------------------------------------------------------------

# Link filedescriptor 10 with stdin
exec 10 $file
    # this checks the return code of echo [not needed for writing; just for demo]
    if [ $? -ne 0 ] 
     then echo "Error in writing to file ${file}; check its permissions!"
    fi
done

echo "Number of lines: $count"
echo "The last line of the file is: `cat ${file}`"

# Note: You can achieve the same by just using the tool wc like this
echo "Expected number of lines: `wc -l $in`"

# restore stdin from filedescriptor 10
# and close filedescriptor 10
exec 0

Chủ Đề