Shell programming
Getting Started with Shell Programming
1.1 Hello World
Printing Hello World
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
Create a file with
.sh
extension usingMake the script executable
+x
makes the file executableopen the file in nano by
Or you can use vim, sublime, VScode or any other text editor you like.
Inside the file, add
Line 1: The first line of the script must start with the character sequence #!, referred to as shebang
The shebang instructs the operating system to run /bin/bash, the Bash shell, passing it the script's path as an argument
Run the file using
OR you can use any of the following
Note : 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
1.2 Hello World using Variables
Create a new file called
hello.sh
Add
Note : spaces cannot be used around the
=
assignment operator
1.3 Hello World with User Input
1.3.1 Reading from console
read
will read input given in a new line until the enter
key is not pressed and will store the value in variable mentioned after the keyword.
1.3.2 Formatting String
1.4 Importance of Quoting in String
There are two types of quoting: \
Weak: uses double quotes:
"
\Strong: uses single quotes:
'
If you want to bash to expand your argument, you can use Weak Quoting:
If you don't want to bash to expand your argument, you can use Strong Quoting:
1.5 Hello World in "Debug" mode
To see which line is running, you can use Debug mode
Create a new file with simple echo hello world
Run the Script using
you will get the following output :
Note : The -x argument enables you to walk through each line in the script
Cat & Alias
Using Cat
Concatenate files
This is the primary purpose of cat
is to concatenate files.
This will add the contents of text1.txt
and text2.txt
to a new files called text3.txt
Printing the Contents of a File
will print the contents of a file.
If the file contains non-ASCII characters, you can display those characters symbolically with cat -v
. This can be quite useful for situations where control characters would otherwise be invisible.
Very often, for interactive use, you are better off using an interactive pager like less
or more
, though. ( less
is far more powerful than more
and it is advised to use less
more often than more
)
In case the content needs to be listed backwards from its end the command tac can be used:
If you want to print the contents with line numbers, then use -n
with cat:
Write to a file
It will let you write the text on terminal which will be saved in a file named file.
will do the same, except it will append the text to the end of the file.
N.B: Ctrl+D
to end writing text on terminal (Linux)
Read from standard input
Output is same as cat file.txt , but it reads the contents of the file from standard input instead of directly from the file.
The echo command before | outputs two lines. The cat command acts on the output to add line numbers.
Display line numbers with output
Use the --number flag to print line numbers before each line. Alternatively, -n
does the same thing.
To skip empty lines when counting lines, use the --number -nonblank
, or simply -b
.
Aliasing
Shell aliases are a simple way to create new commands or to wrap existing commands with code of your own. They somewhat overlap with shell functions, which are however more versatile and should therefore often be preferred.
Create an Alias
Invoking word will run command
. Any arguments supplied to the alias are simply appended to the target of the alias:
To include multiple commands in the same alias, you can string them together with && . For example:
Remove an alias
To remove an existing alias, use:
Bypass an alias
Sometimes you may want to bypass an alias temporarily, without disabling it. To work with a concrete example, consider this alias:
The BASH_ALIASES is an internal bash assoc array
Aliases are named shortcuts of commands, one can define and use in interactive bash instances. They are held in an associative array named BASH_ALIASES. To use this var in a script, it must be run within an interactive shell
List all Aliases
will list all the current aliases.
Jobs
Jobs
To create an job, just append a single & after the command:
$ sleep 10 &
Or run immediately :
sleep 10
To bring the Process to the foreground, the command fg is used together with % :
fg %
Killing running jobs
Navigating & Listing
Navigating Directory
Absolute vs relative directories
To change to an absolutely specified directory, use the entire name, starting with a slash /, thus:
If you want to change to a directory near your current on, you can specify a relative location. For example, if you are already in /home/username/project, you can enter the subdirectory abc thus:
If you want to go to the directory above the current directory, you can use the alias ...
For example, if you were in /home/username/project/abc
and wanted to go to /home/username/project
, then you would do the following:
Change to the last directory
For the current shell, this takes you to the previous directory that you were in, no matter where it was.
Change to the home directory
The default directory is the home directory $HOME
, typically /home/username
,
So cd
without any directory takes you there
Or you could be more explicit: cd $HOME
A shortcut for the home directory is cd ~
, so that could be used as well.
Listing Files
option
description
ls -a | list all files including hidden file starting with '.' ls --color | colored list [=always/never/auto] ls -d | list directories - with ' /' ls -F `add one char of /=>@` | to enteries ls -i | list file's inode index number ls -l | list with long format - show permissions ls -la | list long format including hidden files ls -lh | list long format with readable file size ls -ls | list with long format with file size ls -r | list in reverse order ls -R | list recursively directory tree ls -s | list file size ls -S | sort by file size ls -t | sort by time & date ls -X | sort by extension name |
List Files in a Long Listing Format
The ls command's -l
option prints a specified directory's contents in a long listing format. If no directory is specified then, by default, the contents of the current directory are listed.
Example Output:
The output first displays total, which indicates the total size in blocks of all the files in the listed directory. It then displays eight columns of information for each file in the listed directory.
List the Ten Most Recently Modified Files
The following will list up to ten of the most recently modified files in the current directory, using a long listing format -l
and sorted by time -t
.
List All Files Including Dotfiles
The -a
or --all
option will list all files, including dotfiles
List Files Without Using ls
ls
Use the Bash shell's filename expansion and brace expansion capabilities to obtain the filenames:
To capture a list of files into a variable for processing, it is typically good practice to use a bash array:
List Files in a Tree-Like Format
Use
Output :
List Files Sorted by Size
The ls command's -S option sorts the files in descending order of file size
When used with the -r option the sort order is reversed
Redirection
Redirecting standard output
>
redirect the standard output (akaSTDOUT
) of the current command into a file or another descriptor. These examples write the output of the ls command into the filefile.txt
The target file is created if it doesn't exists, otherwise this file is truncated.
The default redirection descriptor is the standard output or 1 when none is specified. This command is equivalent to the previous examples with the standard output explicitly indicated:
Note: the redirection is initialized by the executed shell and not by the executed command, therefore it is done before the command execution.
Append vs Truncate
Truncate >
Create specified file if it does not exist.
Truncate (remove file's content)
Write to file
Append >>
Create specified file if it does not exist.
Append file (writing at end of file).
Overwrite existing file
Append a second line
Last updated