Laboratorium Komputerowe Progmar
Marcin Załęczny

We are using cookies in the page. If you use the page you agree for the cookies.      Close

Bash - general information

The order of running startup scripts by bash login shell:

  1. /etc/profile - this script among others runs /etc/bash.bashrc and then all *.sh scripts that reside in /etc/profile.d directory. This is the directory you should put any *.sh scripts containing global-wide variables exported for all users in.
  2. Next there is ran first of following files: ~/.bash_profile, ~/.bash_login or ~/.profile. In one of the files you can modify default global settings. In Ubuntu by default, new user account contains in his home directory predefined files: ~/.profile and called from it ~/.bashrc.

During the user logout there is called ~/.bash_logout script.
Interactive non-login shells after theirs start-up call ~/.bashrc. All settings are inherited from login shell.
Non-interactive shells that are used for running other processes and scripts do not run any of specified earlier scripts. However, they inherit global settings from login shell.
Applications, programs and scripts that are ran from crontab neither do not executes any of above start-up scripts nor inherit global settings from the login shell.
Because ~/.bashrc file can be executed multiple times, all commands that modify variables or create new ones should be placed in ~/.profile file.

Builtin Bash variables (positional and special parameters):
$# Amount of arguments passed from command line.
$? Error code of the last executed program.
$$ Shell's PID.
$! PID of the last ran in the background command.
$0 The name of the script being ran.
$1-$9 Arguments passed from command line.
$* All arguments passed from command line as one string: "$1 $2 $3 ...". The values are separated by the first character of $IFS variable (usually space).
$@ The list of all argumnets passed from comand line separated by space character.

"source script" or ". script" - runs specified script within current shell. All changes in environment and variables' content will be taking place in current shell.

-- - two dashes in Bash command line mark the place where program's options ends and arguments starts.

[name=value ...] command
Assigns value for every specified variable and places the variables within command's environment.

Keyboard shortcuts available in command line:

CTRL+D - removes a character before a cursor
CTRL+U - removes all characters before a cursor
CTRL+K - removes all characters after cursor and at the cursor's position
CTRL+W - removes a word before a cursor
CTRL+F - moves cursor one character right
CTRL+B - moves cursor one character left
CTRL+A - moves cursor to the begining of current line
CTRL+E - moves cursor to the end of current line

command >fname - sending standard output of the command to file fname
command <fname - sending content of file fname to standard input of the command
command_1 | command_2 - sending standard output of command_1 to standard input of command_2
command_1 |& command_2 - sending standard output and standard error output of command_1 to standard input of command_2

The return value of the stream is the value returned by last command of the stream.

AND list:
stream_1 && stream_2 - here stream_2 will be executed only when stream_1 finishes with success (its return value is 0).
OR list:
stream_1 || stream_2 - here stream_2 will be executed only when stream_1 finishes with failure (its return value is != 0).

File descriptors and redirection symbols:

0 - standard input
1 - standard output
2 - standard error output

> is synonym for 1> - redirection of standard output
< is synonym for 0< - redirection of standard input
2> - redirection of standard error output
>> - redirection of standard output to a file, if the file already exists then the data is appended to it

&> - redirection of standard output and standard error output to a single file
2>&1 - makes standard error output a duplicate of standard output
2>&1 | lub |& - makes standard error output and standard output a stream to a next command
1>&2 or >&2 - redirection of standard output to standard error output

To run an executable file there is no need to have a read permission to this file. An executable permission is enough.

In the first line of a shell script you can specify what shell or program should execute the file. Just place a full path to the program after the #! sequence, for example:

#!/bin/bash
If in a script a line starts with a # character the the line is a comment.

Control operators:

; - separates commands
new line character - separates commands too
& - means that a program or script have to be runned in the background, separates commands too
| - redirects standard output of a process to a standard input of another process, separates commands too
|& - redirects standard error output of a process to a standard input of another process, separates commands too
() - groups commands, for every group of commands a shell creates a new child shell which runs these commands
&& - logical AND
|| - logical OR, both operators && and || have the same priority
;; - breaks the block of commands

Separated \ character means that the command is countinued in the next line.

Bash makes available to work with a directory stack.
dirs command displays current content of the stack or current working directory if the stack is empty.

pushd directory - puts a specified directory onto the top of the stack, makes the directory a current working directory and displays the stack content.
pushd - swaps two highiest directories on the stack, makes the directory on the top of stack a current working directory and displays the stack content.
pushd +number - moves a directory with specified number to the top of the stack makes the directory a current working directory and displays the stack content. Directories on the stack are numbered with ordered integers starting from 0. The number 0 is assigned to directory on top of the stack, number 1 is assigned to the second directory near the top of the stack and so on.
popd - removes a directory from the top of the stack, makes the directory on the top of stack a current working directory and displays the actual stack content.
popd +number - removes a directory with a given number from the stack. If it was not a directory on the top of the stack then current working directory is not changed. Elsewhere makes the directory on the top of stack a current working directory. Finally displays the stack content.

Local variables in Bash are created by a simple assignment statement, ex.:

my_variable="abc 123"
There must be no spaces inserted before and after the = character. To make the variable global one (available in all programms runned from the current shell) issue the command:
export my_variable
According to the the convention all global variables (called also an environment variables) should be written with capital letters, ex.:
MY_VARIABLE="abc 123"
export MY_VARIABLE
Besides, Bash makes it available to set variables in the command line. The variables are available only for command being run ex.;
MY_DIRECTORY=/home/mzaleczny ./a_script.sh
In the command above the MY_DIRECTORY variable is available only in an environment of a a_script.sh.
To append some text after the variable's value issue a command:
echo ${VARIABLE}appended_text
instead of
echo $VARIABLEappended_text
Because in the second of above examples it will be printed a value of non-existing variable $VARIABLEappended_text - an empty string.
Every command can have up to 99 different parameters. We access them in the following way: $1, $2, ..., $9, $(10}, ${11}, ..., ${99} Next command removes a value of the specified variable:
VARIABLE=
Next command removes a specified variable from the environment of current shell:
unset VARIABLE
Making the specified variable as read-only (there will be unavailable to change this variable's value or to remove the variable from environment):
readonly VARIABLE
or
declare -r VARIABLE=READ_ONLY_VALUE
Read-only variable's attribute cannot be removed. Exporting the variable with the command export is equivalent to the following command:
declare -x VARIABLE
Removing a variable's exported attibute can be done by:
declare +x VARABLE
Lists all read-only variables:
readonly
or
declare -r
Lists all exported variables:
export
or
declare -x
An integer variable can be set by following command:
declare -i LENGTH=32
Lists all integer variables:
declare -i
An array-type variables can be set as below:
declare -a BASH_VERSINFO='([0]="4" [1]="2" [2]="25" [3]="1" [4]="release" [5]="i686-pc-linux-gnu")'
Lists all array-type variables:
declare -a

PS1 variable represents the look and feel of the basic command prompt. It can consist of:

\$ - # character for system administrator and $ for all other users
\h - hostname without domain name
\H - full hostname (together with domain name)
\j - amount of running in background jobs that are managed by current shell
\l - device base name of the terminal which runs current shell
\s - shell's name
\t - 24-hours time in format HH:MM:SS
\T - 12-hours time in format HH:MM:SS
\@ - 12-hours time in format HH:MM
\A - 24-hours time in format HH:MM
\u - current user's name
\v - shortened bash'es version number
\V - full bash'es version number
\w - current working directory
\W - last part of current working directory, ~ if current working directory is a home directory of current user
\d - date in format: shortened week day, shortened month, day of month (ex. "mon sep 28")

PS2 variable represents the secondary command prompt. It is displayed whenever the user enters a command that not ends in the one line and is continued to display in every line that not ends the the command.

IFS (Internal Field Separator) is a variable that holds a string of characters which can represent a word separators (commands, theirs parameters and so on) in a Bash command line. The characters separate words only in a case of substitute variables' values. The characters written directly in a command line not cause words to be separated.
If the characters in IFS are: space, tab character or new line then the multiple occurences of mixings of them is treated as a single separator.
If the characters in IFS are any other than the above then the multiple occurences of mixings of them is treated as a multiple separators.

After the execution of a command in a command line, Bash searches for the command placement in an environment variable called PATH to find the full path to the command. Next, Bash saves the command's full path in its internal hash table. Then following references to the same command results in taking the command's full path from the internal hash table instead of searching PATH directories again. The hash table content can be displayed by the command:

hash
To clear the table issue the command:
hash -r

Creating an alias:

alias name=value
Around the = character cannot be any space character. If value contain spaces then it should be placed within " or ' characters ex.:
alias ll='ls -l'
Aliases should be defined in ~/.bashrc file or in alias dedicated ~/.bash_aliases file.
Displays definition of an alias of specified name:
alias name
Displays definition of all aliases:
alias
Removes specified alias:
unalias name

Calculates specified arithmetic expression and replaces the syntax below with the calculated value:

$((expression)), ex. $((50 -24))
Variables in the expression do not have to be prefixed with $ character. Computed outcome can be assigned to a variable:
wynik=$((wyrazenie))
It is equivalent to:
let "wynik=wyrazenie"

Executes specified command and replaces the syntax below with its standard output:

$(command)

Reads input from user and assigns it to variable $month:

read -p "Enter month number (1-12): " month

Displays a message on the standard error output:

echo "Komunikat" 1>&2