bash command substitution escape sequences and Metacharacters

Bash command substitution escape sequences and Metacharacters

Bash command substitution

we can save output of any command used in Linux to a given variable by using bash command substitution and then we can use this variable in our script.

In bash command substitution we use the backquote, not the single quote character.





Here in this example we used command date to display date of system, like wise we can use any command in bash.



Escape sequences in shell or bash

Here in this example we used \n to get in next line



Note: -e option used to interpretation of backslash escapes.

Now without -e option

Value of a is 55\nNext Line

List of Escape Sequence in bash script

\\ backslash
\a alert (BEL)
\b backspace
\c suppress trailing newline
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab

Variable Substitution in bash script

It is sed to manipulate the value of a variable.

Variable Substitution Example


Some more example with output

Metacharacters in bash or shell script

We can use \ for printing some special character,considering the below example here.



Example 2:

Output :



shell metacharacters in bash script

> Output redirection
cal > file.txt # This puts a current calendar into file.txt

>> Output redirection (append)
date >> file.txt # This append the current date to the end of file.txt

< Input redirection
sort < file.txt # This will print out the contents of file.txt with the lines sorted.

* wildcard, zero or more characters
ls a*.txt # it will display all file which start with a and end with .txt like ahhgty.txt

? wildcard, one character
ls a?.txt # it will display all file which start with a and have only one charecter next and end with .txt like ah.txt

cmd Command Substitution
$(cmd) Command Substitution

| Pipe (|) output of one commang given to input ot another command
cat file.txt | grep kencorner # It will print the lines in file.txt that contain the string “kencorner”

; run multiple command
date;cal; date # Print the date, calender and date again

[ ] wildcard, any character between brackets
ls -l a[bc].txt # it display ab.txt, ac.txt

|| OR conditional execution
mkdir File || echo “mkdir failed!” # if mkdir fail then it will print mkdir failed statement

&& AND conditional execution
mkdir File && echo “Made the directory” # it will print message on succeefull of first command

( ) Group commands, Sequences of Commands
(cal; date) > file.txt # Put a calendar and the date in file.txt

& Background Processes
# Comment
\ Prevent or escape interpretation of the next character

NOTE : The exit command terminates a script,and return a value. If it is sucessful then it will retrn 0 else non-zero.

You May Also Enjoy Reading This …

Leave a Reply

Your email address will not be published. Required fields are marked *