GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing wiki.ubuntu.com — Bash scripting for beginners - Ubuntu Wiki (Redirected from Beginners/BashScripting) This guide begins with useful terminal commands before introducing the basics of scripting with Bash. Note This guide was migrated from the tutorial "Beginners/BashScripting" on the old Ubuntu community wiki. It has been refined and updated to reflect current best practices. Tidying This page has been identified as needing tidying and should be reviewed for clarity, structure, and formatting.
CommandsDuring your time as an Ubuntu user, you will use the terminal to perform various tasks. In this article, we'll discuss the following topics:
Text editorsThere are several editors available in Ubuntu. The most common ones are Nano and Vim. Running them is as simple as invoking them in the terminal. nano vim Nano is probably the easiest to use for absolute beginners. If one is inclined to learn Vim, check out the Vim Tutor that is builtin to Vim. It can be run by invoking the following command: vimtutor Absolute and relative file pathsNote The words "folder" and "directory" mean the same thing and are often used interchangeably. The canonical term is technically "directory", as that is what is used in Unix/Linux manual pages and documentation, but directories can be thought of as folders metaphorically.
An absolute path to a file or directory is the full path starting from the root directory. The following are examples of absolute paths: /home/ubuntu /home/ubuntu/.bashrc /var/log/messages /usr/local/bin /bin/vim A relative path to a file or directory is the path starting from the current working directory; that is, relative to the current working directory. The following are examples of a relative path where we'll assume the current working directory is Downloads/ .bashrc Pictures/photo.jpg .config/autostart .local/share/applications/ For example, suppose the current working directory is vim ../.bashrc
If an absolute path is not specified, Bash assumes the path is relative. For example, if the current working directory is nano Templates/file.txt
Creating directoriesOn Desktop, directories can be created by right clicking in the Nautilus file manager and selecting 'New Folder'. This can also be done with a keyboard shortcut: SHIFT + CTRL + N. To do the same from the terminal, run: mkdir /home/ubuntu/Desktop/new_directory
The To create directories recursively, use mkdir -p ~/files/work/project This ensures that if For more information on the usage of the Deleting files and directoriesDeleting files are done with the rm /home/ubuntu/file_to_be_deleted
To remove a directory and all its contents recursively: Warning The
-r (recursive) flag can result in unintended data loss if used carelessly.rm -r /home/ubuntu/unneeded_directory You can also use the rm -rf /home/ubuntu/unneeded_directory Warning The following commands will result in a broken system because the recursive
-r flag and the force -f flag will forcibly remove the root directory and all its contents. These commands should never be run on a typical workstation or server.
rm -rf /* rm -rf / For more information on the usage of the Running commands as rootWhen working on the command line, you usually want to work with the default permissions. This way you ensure that you won't accidentally break anything belonging to the system or other users, so long as the system and other users haven't altered their file permissions. There will be times when you wish to copy a file to a system directory like cp Downloads/script.sh /usr/local/bin/ cp: cannot create regular file '/usr/local/bin/script.sh': Permission denied For more information on the usage of the As it would be tedious to always login as root to do administrative tasks, you can use sudo to execute a single command with root privileges. Note It's considered good practice to avoid logging in and performing tasks as the root user. Instead, use the
sudo command as a normal user to execute commands with root privileges.sudo cp Downloads/script.sh /usr/local/bin/ The default Ubuntu installation is configured so that the user who was created during system installation is allowed to use the For more information on the usage of the Opening GUI applications as rootSometimes you will want to edit a config file in your root directory, in order to save changes to this file you need root privileges, so you need to open a text editor as root. All you will need is just sudo gedit
Backing up your filesTo create a backup of a file, you can use the cp source_file dest_file This will copy the source file to the destination file. Using the previous example, if you want to backup your Note The
~/ syntax is shorthand for the absolute path to the user's home directory, /home/ubuntu.sudo cp ~/.bashrc ~/.bashrc.backup Suppose you downloaded a GIF titled cp ~/Downloads/dancing_hotdog.gif ~/Pictures/ Warning The destination directory,
~/Pictures, must exist for the copy to succeed. Otherwise you'll get an error: cp: 'Pictures/' is not a directoryBacking up directoriesTo backup one directory to another, use cp -r /home/ubuntu/source_directory /home/ubuntu/backup_directory If you want to copy all of the contents of your cp -r /home/ubuntu/source_directory/ /home/ubuntu/backup_directory Command referenceFor a full command reference, refer to the terminal command reference page. ScriptingTip The commands given in the scripting section are to be put into the text editor and not in the terminal unless instructed otherwise.
Bash is also a scripting language. You can create a bash script by opening your favorite text editor to edit your script and then saving it. Typically a script is saved with a #!/usr/bin/env bash echo "Hello, World" The first line of the script is called the shebang ( Note It's considered a best practice to use
/usr/bin/env bash for the shebang line when writing bash scripts. The reason is because not every Unix-like system has the bash binary available at the /bin/bash path, so the env command instructs the kernel to look for the bash binary in $PATH and use the first occurrence it finds. However, in most Linux systems it is located at /bin/bash.To run a bash script, you first have to have the correct file permissions. We do this with chmod: chmod a+x hello_world.sh # Gives everyone (owner, group, and other) execute permissions chmod 700 hello_world.sh # Gives read, write, execute permissions only to the owner (the ubuntu user, in our case) These permissions allow us the execute the script as a binary. Next, open a terminal and run the script like this: ./hello_world.sh This should print "Hello, World" to the console. VariablesVariables store information (values) that can be used later in the script. To define a variable named var="FOO" The name of the variable (in this case, echo "$var" When accessing the contents of the variable, we usually say we are expanding the variable. It is good practice to use double quotes around a variable when expanding it in a shell script, because sometimes our variable may contain wildcard var="*" echo $var The result printed to the console will be: Desktop Documents Downloads Music Pictures Templates Videos This is because the wildcard captures whatever is in the current working directory. However, if we were to use double quotes around the variable expansion, we'll get the variable's literal value: var="*" echo "$var" Output: * Variables can also be expanded inside other variables. For example, suppose we want to set a path to a directory containing backup archives. BACKUP_DIR="/home/ubuntu/backup" Now suppose we want to append a backup archive's filename to ARCHIVE_FILE="${BACKUP_DIR}/archive_file.tar.gz" This expands to When the value of a variable contains another variable preceded or followed by a string, it is good practice to surround the inner variable name with braces We'll write a simple backup script that backs up the contents of the #!/usr/bin/env bash PICTURES_DIR="/home/ubuntu/Pictures" CURRENT_DATE=$(date '+%Y-%m-%d') tar cvfz "Pictures-backup-${CURRENT_DATE}.tar.gz" "$PICTURES_DIR" Make this script executable, and then execute it: chmod +x pictures_backup.sh ./pictures_backup.sh The resulting archive file will be in the current working directory: If statementsAn if [ "$EDITOR" == "vim" ]; then echo "Editor is vim" elif [ "$EDITOR" == "nano" ]; then echo "Editor is nano" else echo "Unknown editor" fi Depending on your use-case, the if [ "$EDITOR" == "vim" ]; then vim --version fi ...remainder of script... Storing application stdout to a variableApplication ExamplefooVar=$(who) echo $fooVar This code should output the current users, their respective ttys, and date of login. Note that this strips newlines. Be sure to do any parsing in-line ( | grep, etc ) and then pass it to a variable. We will try this again, but grep for tty7, the GUI's tty. Example 2fooVar=$(who | grep tty7) echo $fooVar This should output the single user that is currently logged in. FunctionsBash lets you create a function on the fly, which is handy if you plan on using a code block more than once. Functions are typically used when you have a set of tasks you want to run more than once in the script, potentially with different inputs. ExampleHere is an example script: echo "echo is Called" echo "Functions are FUN!" echo "echo is Called" Although this example is simple, you can see that if you want to change "echo is Called" to say "foo is Called" you would have to edit twice. Below is the same app using functions. echoFunction() { echo "echo is Called" } fooBar() { echo "Functions are FUN!" } echoFunction; fooBar; echoFunction; The script is longer now, but if you want to change the To show how functions can receive inputs, consider the following example: greeting() { echo "Hello, ${1}." } greeting "Ubuntu" # Output: Hello, Ubuntu. The distro_info() { echo "Ubuntu ${1} is a Linux distribution for ${2}." } distro_info "Desktop" "desktops" # Output: "Ubuntu Desktop is a Linux distribution for desktops." distro_info "Server" "servers" # Output: "Ubuntu Server is a Linux distribution for servers." Arguments supplied to functions are separated by surrounding them with quotes. In the example above, "Desktop" is substituted in place of DebuggingIt can be useful to trace a script to find out why something does not work as expected. To trace, start it through Bash explicitly and use the bash -x ./script.sh This will write each command to standard error (preceded by a ‘+ ’) before it is executed. Other Scripting Languages related to BashtrThis is one of the most basic applications to pipe data through that uses a basic scripting syntax. In this case, it accepts regular expressions. Let's do a normally complicated task, transforming a string to all uppercase. read foo var=$(echo $foo | tr "{a-z}" "{A-Z}") # {a-z} Matches a through z # {A-Z} matches A through Z echo $var The output should look something like this: this is a test THIS IS A TEST We can also use echo "Type in: I love tars" read foo var=$(echo $foo | tr "t" "b") echo $var The output should look something like this: I love tars I love bars AWKAWK is short for Aho, Weinberger & Kernighan. It has its own custom scripting language, suitable for a page all by itself, so here we will only look at some basics I will cover only the basics that can help when you are bash scripting. pidof cloneLet's make a quick pidof clone that prompts for a process identifier, then echoes the process ID: read pname ps -ef | grep -v grep | grep $pname | awk '{print $2}' Let's take some pipes out and use only awk for the filtering: read pname ps -ef | awk -v p=${pname} '$8 ~ p { print $2 }' Single quotes are used to pass the awk command(s). The curly braces are to use the awk language (for prints, ifs, etc.). The There are a lot more commands than the print command, including if statements, and it is worth looking into if you are interested in using awk. SEDOnly the Try this out to show that sed can not only replace in-line, but, unlike tr, can replace a string with a longer or shorter string than before: read foo echo $foo | sed "s/foo/bars/" When this command is run, it should substitute the first appearance of "foo" with "bars". This is an example of the output. I love to go to foo I love to go to bars |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |