LPI E - Scripting
LPI E - Scripting
3.3 Turning Commands into a Script
Review of Topics- Part 1 of 2
Part Two: Editors
Linux Command Line Interface (CLI) is a powerful tool that allows users to execute commands in a text-based interface. One of the most useful features of the Linux CLI is the ability to turn a series of commands into a Bash script. This can be particularly useful when performing repetitive tasks or automating complex processes.
In this blog post, we will provide in-depth instructions on how to use Linux Command Line Interface for turning commands into a Bash script.
We will cover topics such as using
- "/bin/bash"
- variables
- arguments
- "for loops"
- echo
- the exit status.
Using "/bin/bash"
The first step in creating a Bash script is to define the interpreter that will be used to run the script. This is done using the shebang line at the beginning of the script. The shebang line consists of the characters #! followed by the path to the interpreter. In most cases, the interpreter used for Bash scripts is /bin/bash.
#!/bin/bash
BASH is the default interpreter on most Linux distributions, and it is installed by default. However, some other interpreters that are often installed by default on Linux distributions include:
- Dash: A lightweight shell that is used as the default system shell on some Linux distributions.
- Korn shell (ksh): A shell that is compatible with the Bourne shell (sh) and includes many advanced features.
- Zsh: A powerful shell that includes many advanced features, such as advanced tab completion and built-in spelling correction.
- Tcsh: A shell that is an enhanced version of the C shell (csh) and includes many advanced features, such as command line editing and job control.
Note that while these shells are often installed by default on Linux distributions, they may not be installed on all systems or may not be the default shell.
Here are some example snippets for defining each of the optional interpreters in a shell script:
Dash:
#!/bin/sh -
Note that the dash symbol (-) at the end of the shebang line is optional but can be used to prevent the shell from reading any options that may be passed to the script.
Korn shell (ksh):
#!/bin/ksh
Zsh:
#!/usr/bin/zsh
Tcsh:
#!/bin/tcsh
Tips and Tricks for choosing an interpreter
💃📣
- Compatibility: If you are writing scripts that will be run on multiple systems, consider using a shell that is compatible with the Bourne shell (sh), such as Dash or Korn shell.
- Features: Consider using a shell that includes advanced features if you need them, such as Zsh or Tcsh.
- Performance: If performance is a concern, consider using a lightweight shell, such as Dash.
- Personal preference: Ultimately, the choice of which shell interpreter to use may come down to personal preference, so experiment with different shells and use the one that you find most comfortable and efficient.
Declaring Variables
Variables can be declared in a Bash script using the following syntax: variable_name=value. Variables in Bash scripts are typically used to store temporary or permanent data that is needed during the execution of the script
name="John"
echo $name
Tips and Tricks for declaring variables
💃📣
Declaring variables in Linux Shell scripts is a fundamental concept that allows you to store and manipulate data within your scripts. Here are some tips and tricks to consider when working with variables in Shell scripts:
- Naming conventions: When naming your variables, use descriptive names that are easy to understand and remember. Variable names should start with a letter or underscore, and can only contain letters, numbers, and underscores.
- Variable types: In Shell scripts, variables are untyped, which means that you do not need to specify their data type when you declare them. The Shell will automatically determine the type of data that the variable holds based on the value that you assign to it.
- Variable assignment: To assign a value to a variable, use the following syntax:
- $ variable_name=value
Note that there should be no spaces between the variable name, the equals sign, and the value.
- Accessing variables: To access the value of a variable, prefix the variable name with a dollar sign ($) like this:
- $ echo $variable_name
Note that when accessing a variable, you do not need to include the dollar sign when you assign a value to it.
- Variable scope: In Shell scripts, variables are global by default, which means that they can be accessed from any part of the script. However, if you want to limit the scope of a variable to a specific part of the script, you can use the local keyword.
- $ local variable_name=value
- Variable substitution: You can use variable substitution to include the value of a variable within a string. There are three ways to do this:
- # Method 1: Use double quotes
- $ echo "Hello, $name!"
- # Method 2: Use curly braces
- $ echo "Hello, ${name}!"
- # Method 3: Use concatenation
- $ echo "Hello, " $name "!"
Note that when using concatenation, you need to include spaces between the strings and the variable.
- Exporting variables: If you want to make a variable available to other scripts or processes, you can export it using the export command.
- $ export variable_name=value
- Read-only variables: If you want to prevent a variable from being modified, you can declare it as read-only using the readonly keyword.
- $ readonly variable_name=value
- Default variable values: If you want to assign a default value to a variable in case it is not set, you can use the following syntax:
- $variable_name=${variable_name:-default_value}
This will assign the value "default_value" to the variable if it is not already set.
By following these tips and tricks, you can make your Shell scripts more robust and easier to maintain.
💃📣
Using Arguments
Bash scripts can take arguments from the command line when they are executed. These arguments are stored in special variables, which are accessed using the $ symbol followed by a number. $0 represents the name of the script, $1 represents the first argument, $2 represents the second argument, and so on.
#!/bin/bash
echo "The first argument is: $1"
echo "The second argument is: $2"
#!/bin/bash
echo "The script name is: $0"
echo "The first argument is: $1"
echo "The second argument is: $2"
echo "The third argument is: $3"
Here's an example of running this script with arguments:
$ ./script.sh foo bar baz
The script name is: ./script.sh
The first argument is: foo
The second argument is: bar
The third argument is: baz
You can use these arguments to perform different actions in your script, depending on what values are passed to it. For example, you could use the arguments to specify a file name or a search string.
Note that you can access arguments beyond $3 by using the special $@ variable, which contains all of the arguments passed to the script. For example, $4, $5, and so on can be accessed as $@ with a numeric index, like ${@:4}.
💃📣
- Positional Parameters: When passing arguments to a shell script, they are referred to as positional parameters. These parameters are numbered starting with 1, and can be accessed in the script using the syntax $1, $2, $3, etc. For example:
- #!/bin/bash
- echo "The first argument is: $1"
- echo "The second argument is: $2"
- echo "The third argument is: $3"
If this script is called with the command ./script.sh arg1 arg2 arg3, it will output:
The third argument is: arg3
- Handling Multiple Arguments: When a shell script needs to accept multiple arguments, it can be cumbersome to use the positional parameters ($1, $2, etc.). Instead, the special parameter $@ can be used to represent all the arguments passed to the script. For example:
- #!/bin/bash
- for arg in "$@"
- do
- echo "Argument: $arg"
- done
If this script is called with the command ./script.sh arg1 arg2 arg3, it will output:
Argument: arg1
Argument: arg2
Argument: arg3
- Named Parameters: Another way to pass arguments to a shell script is to use named parameters. This is often more readable and maintainable than using positional parameters. The getopts command can be used to handle named parameters in a shell script. For example:
while getopts ":a:b:" opt; do
case $opt in
a) arg1="$OPTARG"
;;
b) arg2="$OPTARG"
;;
\?) echo "Invalid option -$OPTARG" >&2
;;
esac
done
echo "arg1 = $arg1"
echo "arg2 = $arg2"
arg1 = arg1
arg2 = arg2
- Error Handling: When passing arguments to a shell script, it's important to handle errors gracefully. This can be done using the if statement and the $# variable, which represents the number of arguments passed to the script. For example:
if [ $# -ne 2 ]; then
echo "Usage: script.sh arg1 arg2"
exit 1
fi
echo "arg1 = $1"
echo "arg2 = $2"
If this script is called with the command ./script.sh arg1, it will output:
Usage: script.sh arg1 arg2
And then it will exit with status code 1.
💃📣
Using For Loops
For loops are a useful construct in Bash scripts for iterating over a set of values. The basic syntax for a for loop in Bash is as follows:
for variable in values
do
command1
command2
done
#!/bin/bash
for i in 1 2 3 4 5
do
echo $i
done
1
2
3
4
5
Explanation:
The loop iterates through the list of values 1 2 3 4 5 and assigns each value to the variable i in turn. Then it executes the command echo $i to print the value of i to the terminal. The output shows each value of i printed on a new line.
Using Echo
Echo is a command in Bash that is used to print output to the terminal. It can be used to print variables, text, or a combination of both.
#!/bin/bash
name="John"
echo "Hello, $name!"
Here are some tips and tricks for using echo with BASH scripting in Linux:
💃📣
Printing variables: You can use echo to print the values of variables. Just put the variable name inside $() to print its value. For example:
#!/bin/bash
name="John"
echo "Hello, ${name}!"
Output:
Hello, John!
Printing formatted output: You can use echo to print formatted output using escape sequences. Some commonly used escape sequences are:
- \n: Newline
- \t: Tab
- \b: Backspace
- \r: Carriage return
For example:
#!/bin/bash
echo "Name:\tJohn Smith\nAge:\t30"
Output:
Name: John Smith
Age: 30
Redirecting output to a file: You can use the > operator to redirect the output of echo to a file. For example:
#!/bin/bash
echo "Hello, world!" > output.txt
This will create a new file named output.txt in the current directory and write the text "Hello, world!" to it.
Appending output to a file: You can use the >> operator to append the output of echo to a file. For example:
#!/bin/bash
echo "Line 1" > output.txt
echo "Line 2" >> output.txt
This will create a new file named output.txt in the current directory and write the text "Line 1" to it. It will then append the text "Line 2" to the same file on a new line.
Using echo with command substitution: You can use echo with command substitution to print the output of a command. For example:
#!/bin/bash
echo "The current directory is: $(pwd)"
This will print the text "The current directory is:" followed by the output of the pwd command (which prints the current working directory).
I hope these tips help you in your BASH scripting adventures!
💃📣
Using the Exit Status
The exit status is a value that is returned by a command when it completes. A value of 0 indicates that the command completed successfully, while a non-zero value indicates an error.
#!/bin/bash
ls /tmp
if [ $? -eq 0 ]
then
echo "The directory exists."
else
echo "The directory does not exist."
fi
file1.txt
file2.txt
file3.txt
The directory exists.
Explanation:
The code first executes the command ls /tmp to list the contents of the /tmp directory. If the command succeeds (i.e., the directory exists), it will return an exit status of 0. The next line uses the special shell variable $? to retrieve the exit status of the previous command.
The if statement then checks if the exit status is equal to 0 (which indicates success). If it is, the script prints the message "The directory exists." using the echo command. Otherwise, if the exit status is non-zero (which indicates an error), the script prints the message "The directory does not exist." instead.
In this case, the ls /tmp command succeeds and returns a list of files in the /tmp directory, so the if statement prints "The directory exists." to the terminal.
Working with the PATH
The PATH is an environment variable in Linux that contains a list of directories where the system looks for executable files. It can be modified in a Bash script to add directories to the search path.
#!/bin/bash
PATH=$PATH:/usr/local/bin
In Linux and other Unix-like operating systems, the PATH environment variable is used to specify a list of directories where the system should look for executable files. When you type a command in the shell, the system searches each directory in PATH in order to find the executable file that corresponds to the command.
You can view the value of the PATH variable by typing echo $PATH in the terminal:
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
The PATH variable is usually set in the shell initialization files (e.g. .bashrc, .bash_profile, etc.) or in system-wide initialization files (e.g. /etc/profile.d/ directory files) during system boot. You can also modify the PATH variable directly from the command line using the export command:
$ export PATH=$PATH:/new/directory/path
In the above example, we add a new directory path /new/directory/path to the existing PATH variable. This change is temporary and will only persist for the duration of the current shell session.
You can also modify the PATH variable within a shell script. For example, if you have a script that needs to use a program located in a non-standard directory, you can modify the PATH variable within the script to include that directory:
#!/bin/bash
export PATH=$PATH:/new/directory/path
# now you can run the program from the non-standard directory
program_name
In this example, we export the modified PATH variable to include the directory containing the necessary program. This ensures that the program can be found and executed by the script.
In summary, PATH is a crucial environment variable that helps the system find and execute executable files. You can modify PATH from the command line or within shell scripts to include directories that contain the executables you need to run.
Defining the Interpreter
In addition to the shebang line, the interpreter for a Bash script can also be defined using the -x option followed by the path to the interpreter.
#!/usr/bin/env -x bash
When you execute a script with the shebang line #!/usr/bin/env -x bash, the shell will run in debug mode and display verbose output of each command executed in the script. Here's an example output of such a script:
+ echo 'This is a debug message.'
This is a debug message.
+ mkdir /tmp/test
+ cd /tmp/test
+ touch file1.txt
+ touch file2.txt
+ ls
file1.txt file2.txt
The + sign at the beginning of each line indicates that the shell is in debug mode, and shows the commands executed by the script.
The #!/usr/bin/env part of the shebang line specifies the interpreter to use for the script, in this case /usr/bin/env. The -x option enables debug mode, and bash specifies that the script should be interpreted by the Bash shell.
Note that the -x option is not necessary to execute a Bash script, and it is usually used for debugging purposes to trace the execution of the script. If you remove the -x option, the script will run normally without displaying the debug output.
Using Quotes with Variables
Quotes can be used with variables in Bash scripts to ensure that spaces and special characters are preserved.
#!/bin/bash
name="John Smith"
echo "Hello, \"$name\"!"
Explanation:
#!/bin/bash
This is the shebang line that specifies the interpreter to use for the script, in this case, Bash.
name="John Smith"
This line assigns the string "John Smith" to a variable named name. The variable is defined without a dollar sign, which is the correct syntax for assigning a value to a variable.
echo "Hello, \"$name\"!"
This line prints a message to the terminal. The echo command is used to output text to the console. The message includes the value of the name variable, which is enclosed in double quotes. The backslash before the double quotes is an escape character that tells Bash to treat the quotes as part of the string, rather than as string delimiters.
When this script is executed, the output to the console will be:
Hello, "John Smith"!
Note that the double quotes around $name are important. Without the quotes, if the variable contained whitespace or special characters, they would not be preserved in the output.
Running Arguments into Scripts
Bash scripts can be designed to accept input from the user in the form of command line arguments. This is a powerful feature that allows scripts to be customized for different use cases without having to modify the script itself.
To accept input from the command line, Bash scripts use positional parameters. Positional parameters are a series of variables that are automatically created by the shell when the script is executed. The first positional parameter is stored in $1, the second in $2, and so on.
For example, if we have a script called "greeting.sh" that accepts a person's name as a command line argument, we could write the following script:
#!/bin/bash
echo "Hello, $1!"
If we run this script with the command ./greeting.sh John, it will output "Hello, John!" to the console.
We can also use positional parameters to accept multiple arguments. For example, if we have a script called "sum.sh" that calculates the sum of two numbers, we could write the following script
#!/bin/bash
sum=$(($1 + $2))
echo "The sum of $1 and $2 is $sum."
If we run this script with the command ./sum.sh 5 7, it will output "The sum of 5 and 7 is 12." to the console.
Conditional Loops
Conditional loops are a powerful feature in Bash scripts that allow the script to perform different actions based on the outcome of a test. Bash scripts use the "if" statement to implement conditional loops.
The basic syntax for an "if" statement in Bash is as follows:
if test_condition
then
command1
command2
else
command3
command4
fi
The "test_condition" can be any valid test that returns either true or false. The "then" statement is executed if the test is true, and the "else" statement is executed if the test is false.
For example, if we have a script called "test.sh" that checks if a file exists, we could write the following script:
#!/bin/bash
if [ -f "$1" ]
then
echo "The file $1 exists."
else
echo "The file $1 does not exist."
fi
If we run this script with the command ./test.sh myfile.txt, it will output "The file myfile.txt exists." if the file exists, or "The file myfile.txt does not exist." if the file does not exist.
Conclusion
In this blog post, we have covered in-depth instructions on how to use Linux Command Line Interface for turning commands into a Bash script. With this knowledge, you can start to create Bash scripts to automate your daily tasks and make your life easier.
Disclaimer:
The samples provided here are intended to serve as a
general guide and reference for individuals preparing for the LPI Linux
certifications. These samples are not meant to represent the exact
questions that may appear on the actual exam. The LPI certification
exams are constantly updated and revised, and the questions on each exam
are carefully crafted to assess a candidate's knowledge and skills.
Therefore,
while we have made every effort to ensure the accuracy and relevance of
the samples provided, we cannot guarantee that they will reflect the
content or difficulty level of the actual exam. Additionally, we do not
endorse or have any affiliation with the Linux Professional Institute
(LPI).
We strongly recommend that candidates use these samples as
an additional resource for their exam preparation, in combination with
other study materials and practice tests. Ultimately, success on the LPI
Linux certification exams will depend on an individual's knowledge,
experience, and understanding of the exam objectives.
By using
these samples, you agree that neither the provider of these sample
questions nor any of its affiliates or employees shall be liable for any
damages arising from your use or reliance on these sample questions or
any information provided herein.
Comments