Part 1 · Basics · Lesson 03 · 40 minutes
Use variables, write a script and make aliases
- Use variables, quotes and wildcards in a command
- Write and run your first shell script
- Make an alias and keep it in your start file
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your team lead has watched you type fast, and now she asks for two small things that you can show her. One is a script in your lab that greets a name. The other is an alias, a short name for a long command that you repeat. To build them you need the parts that sit between the keys and the programs: variables, quotes and wildcards.
Recall
What does the key sequence Ctrl+R do, and how do you leave it without running a line?
Ctrl+R searches the history while you type. Ctrl+G leaves the search and runs nothing. Esc leaves it and keeps the found line at the prompt, so that you can edit it.
You press Ctrl+Z in a running program. What happened, and how do you get it back?
The program is frozen, not dead. jobs lists it, and fg wakes it.
The idea
Before the shell runs a line, it changes the line. It replaces aliases (short names), then variables ($name), then wildcards (*.txt), and it takes the quotes away. The quotes that you type decide which of these changes happen. The program then gets the finished words.
- Alias → Variables: a short name becomes a long command
- Variables → Wildcards: $name becomes its text
- Wildcards → Quotes removed: *.txt becomes a list of files
- Quotes removed → Program runs: the program gets the finished words
A script is a file that holds lines for the shell. The shell treats a line of a script as it treats a line that you type.
Worked example
1. Use variables, quotes and wildcards
A variable holds a text. name=Ada sets one (no spaces around =), and $name reads it. Quotes decide what the shell changes before the command runs. Inside double quotes "...", the shell replaces $name and keeps the spaces together. Inside single quotes '...', every character stays as typed. A wildcard is a pattern that the shell replaces with the names of the matching files: * matches any text, and ? matches exactly one character. Quotes switch a wildcard off. touch makes an empty file for each name that you give (lesson 4 says more). && between two commands runs the second one only if the first one worked (lesson 6 says more), so mkdir ... && cd ... moves you into the folder only when it exists.
mkdir -p ~/krlab/linux-basics/glob && cd ~/krlab/linux-basics/glob
name=Ada
echo "hi $name"
echo 'hi $name'
touch a.txt b.txt c.log
ls *.txt
ls ?.log
ls "*.txt"hi Ada
hi $name
a.txt
b.txt
c.log
ls: cannot access '*.txt': No such file or directoryThe rule: use double quotes when a text holds a variable or a space, use single quotes when a $ must stay as typed, and use no quotes when you want the wildcard to work.
2. Write your first script
A script is a text file of commands. The first line starts with #!, and the path after it names the program that runs the file. A line that starts with # is a comment, and the shell skips it. In a script, $1 holds the first word that you give after the name of the script.
printf prints text from a template, and \n in it is a line end. The single quotes (step 1) keep $1 as typed, so that it goes into the file. cat prints a file. Make hello.sh and read it.
mkdir -p ~/krlab/linux-basics/shell
cd ~/krlab/linux-basics/shell
printf '#!/bin/bash\n# hello.sh - greets the name that you give\necho "hello, $1"\n' > hello.sh
cat hello.sh
bash hello.sh Ada#!/bin/bash
# hello.sh - greets the name that you give
echo "hello, $1"
hello, AdaTo start the file by its own name, it needs the execute permission. chmod +x (change mode, add execute) gives it. Lesson 10 explains permissions. The shell starts a program from ./ because the list of folders where it looks for programs, called PATH, does not hold your current folder.
./hello.sh Ada
chmod +x hello.sh
./hello.sh Ada
echo "$PATH"bash: ./hello.sh: Permission denied
hello, Ada
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binYour PATH can be longer. The folders are split by :.
3. Make short names with aliases
An alias is a short name for a longer command. alias NAME='COMMAND' makes one, alias alone lists them, type NAME shows what a name is, and unalias NAME removes it.
alias lh='ls -lh'
alias
type lh
lh ~/krlab/linux-basics/sizes
unalias lh
lhalias lh='ls -lh'
lh is aliased to `ls -lh'
total 12K
-rw-rw-r-- 1 you you 38 Nov 21 10:46 medium.txt
-rw-rw-r-- 1 you you 3.9K Nov 21 10:46 numbers.txt
-rw-rw-r-- 1 you you 5 Nov 21 10:46 small.txt
bash: lh: command not foundThe list of your system holds other aliases as well. An alias lives only in the terminal where you made it. To keep it, add the line to ~/.bashrc, the file that every new interactive bash reads at its start. >> adds text to the end of a file and does not replace the file. source reads a file into the shell that runs now.
echo "alias lh='ls -lh'" >> ~/.bashrc
source ~/.bashrc
alias lhalias lh='ls -lh'To remove the line again, use sed -i (stream editor, change the file in place): '/^alias lh=/d' deletes every line that starts with alias lh=. unalias lh removes the alias from this terminal. Lesson 7 shows the editors.
sed -i '/^alias lh=/d' ~/.bashrc
unalias lhYour turn
Do the two jobs of your team lead. There are no steps here.
In ~/krlab/linux-basics/shell:
- Write a script
welcome.shthat printsWelcome,and then its first argument. Its first line must start the file with bash. - Make it runnable by its own name, and run it with the name
Ravi. - Make the alias
lszforls -lSin your terminal, and read it back withalias lsz. - Set
who=Raviand print the texthello $whoonce with double quotes and once with single quotes. - Make the files
x1.log,x2.log,x3.log,x10.logandnotes.txt, and list the logs with a pattern that matches exactly one character after thex.
Last, make lsz permanent in ~/.bashrc, open a new terminal and test it. Then remove that line again with sed -i.
Check yourself
Why does "hello.sh Ada" say "command not found", when the file is in the folder?
The shell looks for a program only in the folders of PATH, and the current folder is not in it. Write ./hello.sh, which gives the path.
You made an alias, and your script does not know it. Why?
Aliases belong to the interactive shell where you made them. A script starts a new shell, which does not read them. Use the real command in a script.
What does the shell print for echo "$HOME" and for echo '$HOME'?
With double quotes it replaces the variable and prints your home folder, for example /home/you. With single quotes it prints the text $HOME as typed.
Why does "ls *.txt" print an error when no file ends in .txt?
The shell finds no match, so it leaves the pattern as it is, and ls looks for a file that is really named *.txt. The wildcard is replaced only when something matches.
Field notes
- A file such as
~/.bashrcruns at every start of a shell. An attacker who can write to it can add an alias, for example forsudo, to steal a password. MITRE ATT&CK names this "Unix Shell Configuration Modification" (T1546.004). On a suspect account, read the file and runtype sudo. alias rm='rm -i'asks before each delete, but it gives a false feeling of safety: it is missing on other machines and in scripts. A habit that you check is safer.echo $SHELLprints your login shell, the one that the system starts when you log in.echo $0prints the shell that runs now, and it can start with a dash (-bash) in a login shell. The last field of your account line holds the login shell. Accounts that nobody should log in to get the shell/usr/sbin/nologin, which ends the login at once.