Execute Commands with the Bash Shell
Objectives
Save time when running commands from a shell prompt with Bash shortcuts.
Basic Command Syntax
The GNU Bourne-Again Shell (bash) is a program that interprets commands that the user types. Each string that is typed into the shell can have up to three parts: the command, options (which usually begin with a hyphen - or double hyphen -- characters), and arguments. Each word that is typed into the shell is separated from other words with spaces. Commands are the names of programs that are installed on the system. Each command has its options and arguments.
When you are ready to execute a command, press the Enter key. Type each command on a separate line. The command output is displayed before the following shell prompt appears.
[user@host ~]$ whoami
user
[user@host ~]$
To type more than one command on a single line, use the semicolon (;) as a command separator. A semicolon is a member of a class of characters called metacharacters that have a special interpretation for bash. In this case, the output of both commands is displayed before the following shell prompt appears.
The following example shows how to combine two commands (command1 and command2) on the command line.
[user@host ~]$ command1 ; command2
command1 output
command2 output
[user@host ~]$
Write Simple Commands
The date command displays the current date and time. The superuser or a privileged user can also use the date command to set the system clock. Use the plus sign (+) as an argument to specify a format string for the date command.
[user@host ~]$ date
Sun Feb 27 08:32:42 PM EST 2022
[user@host ~]$ date +%R
20:33
[user@host ~]$ date +%x
02/27/2022
The passwd command with no options changes the current user's password. To change the password, first specify the original password for the account. By default, the passwd command is configured to require a strong password, to consist of lowercase letters, uppercase letters, numbers, and symbols, and not to be based on a dictionary word. A superuser or privileged user can use the passwd command to change another user's password.
[user@host ~]$ passwd
Changing password for user user.
Current password: old_password
New password: new_password
Retype new password: new_password
passwd: all authentication tokens updated successfully.
Linux does not require file name extensions to classify files by type. The file command scans the compiled header of a file for a 2-digit magic number and displays its type. Text files are recognized because they are not compiled.
[user@host ~]$ file /etc/passwd
/etc/passwd: ASCII text
[user@host ~]$ file /bin/passwd
/bin/passwd: setuid ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=a467cb9c8fa7306d41b96a820b0178f3a9c66055, for GNU/Linux 3.2.0, stripped
[user@host ~]$ file /home
/home: directory
View the Contents of Files
The cat command is often used in Linux. Use this command to create single or multiple files, view the contents of files, concatenate the contents from various files, and redirect contents of the file to a terminal or to files.
The following example shows how to view the contents of the /etc/passwd file:
[user@host ~]$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
...output omitted...
To display the contents of multiple files, add the file names to the cat command as arguments:
[user@host ~]$ cat file1 file2
Hello World!!
Introduction to Linux commands.
Some files are long and might need more space to be displayed than the terminal provides. The cat command does not display the contents of a file as pages. The less command displays one page of a file at a time and you can scroll at your leisure.
Use the less command to page forward and backward through longer files than can fit on one terminal window. Use the UpArrow key and the DownArrow key to scroll up and down. Press q to exit the command.
The head and tail commands display the beginning and the end of a file, respectively. By default, these commands display 10 lines of the file, but they both have a -n option to specify a different number of lines.
[user@host ~]$ head /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
[user@host ~]$ tail -n 3 /etc/passwd
gdm:x:42:42::/var/lib/gdm:/sbin/nologin
gnome-initial-setup:x:980:978::/run/gnome-initial-setup/:/sbin/nologin
dnsmasq:x:979:977:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin
The wc command counts lines, words, and characters in a file. Use the -l, -w, or -c options to display only the given number of lines, words, or characters, respectively.
[user@host ~]$ wc /etc/passwd
41 98 2338 /etc/passwd
[user@host ~]$ wc -l /etc/passwd ; wc -l /etc/group
41 /etc/passwd
63 /etc/group
[user@host ~]$ wc -c /etc/group /etc/hosts
883 /etc/group
114 /etc/hosts
997 total
Understand Tab Completion
With tab completion, users can quickly complete commands or file names after typing enough at the prompt to make it unique. If the typed characters are not unique, then pressing the Tab key twice displays all commands that begin with the typed characters.
[user@host ~]$ pasTab+Tab1
passwd paste pasuspender
[user@host ~]$ passTab 2
[user@host ~]$ passwd
Changing password for user user.
Current password:
1
Press Tab twice.
2
Press Tab once.
Tab completion helps to complete file names when typing them as arguments to commands. Press Tab to complete as much of the file name as possible. Pressing Tab a second time causes the shell to list all files that the current pattern matches. Type additional characters until the name is unique, and then use tab completion to complete the command.
[user@host ~]$ ls /etc/pasTab 1
[user@host ~]$ ls /etc/passwdTab 2
passwd passwd-
1
Press Tab once.
2
Press Tab once.
Use the useradd command to create users on the system. The useradd command has many options that might be hard to remember. By using tab completion, you can complete the option name with minimal typing.
[root@host ~]# useradd --Tab+Tab 1
--badnames --gid --no-log-init --shell
--base-dir --groups --non-unique --skel
--btrfs-subvolume-home --help --no-user-group --system
--comment --home-dir --password --uid
--create-home --inactive --prefix --user-group
--defaults --key --root
--expiredate --no-create-home --selinux-user
1
Press Tab twice.
Write a Long Command on Multiple Lines
Commands with many options and arguments can quickly become long and are automatically wrapped by the command window when the cursor reaches the right margin. Instead, type a long command by using more than one line for easier reading.
To write one command in more than one line, use a backslash character (\), which is referred to as the escape character. The backslash character ignores the meaning of the following character.
Previously, you learned that to complete a command entry, you press the Enter key, the newline character. By escaping the newline character, the shell moves to a new command line without executing the command. This way, the shell acknowledges the request by displaying a continuation prompt on an empty new line, which is known as the secondary prompt, and uses the greater-than character (>) by default. Commands can continue over many lines.
One issue with the secondary prompt's use of the greater-than character (>) is that new learners might mistakenly insert it as part of the typed command. Then, the shell interprets a typed greater-than character as output redirection, which the user did not intend. Output redirection is discussed in an upcoming chapter. This course book does not show secondary prompts in screen outputs, to avoid confusion. A user still sees the secondary prompt in their shell window, but the course material intentionally displays only the characters to be typed, as demonstrated in the following example.
[user@host ~]$ head -n 3 \
/usr/share/dict/words \
/usr/share/dict/linux.words
==> /usr/share/dict/words <==
1080
10-point
10th
==> /usr/share/dict/linux.words <==
1080
10-point
10th
Display the Command History
The history command displays a list of previously executed commands that are prefixed with a command number.
The exclamation point character (!) is a metacharacter to expand previous commands without retyping them. The !number command expands to the command that matches the specified number. The !string command expands to the most recent command that begins with the specified string.
[user@host ~]$ history
...output omitted...
23 clear
24 who
25 pwd
26 ls /etc
27 uptime
28 ls -l
29 date
30 history
[user@host ~]$ !ls
ls -l
total 0
drwxr-xr-x. 2 student student 6 Feb 27 19:24 Desktop
...output omitted...
[user@host ~]$ !26
ls /etc
abrt hosts pulse
adjtime hosts.allow purple
aliases hosts.deny qemu-ga
...output omitted...
The arrow keys help to navigate through previous commands in the shell's history. The UpArrow edits the previous command in the history list. The DownArrow edits the next command in the history list. The LeftArrow and RightArrow move the cursor left and right in the current command from the history list so that you can edit the command before running it.
Use either the Esc+. or Alt+. key combination simultaneously to insert the last word of the previous command at the cursor's current location. The repeated use of the key combination replaces that text with the last word of earlier commands in history. The Alt+. key combination is particularly convenient, because you can hold down Alt and press . repeatedly to quickly cycle earlier commands.
Edit the Command Line
When used interactively, bash has a command-line editing feature. Use the text editor commands to move around and modify the currently typed command. Using the arrow keys to move within the current command and to step through the command history was introduced earlier in this section. The following table shows further powerful editing commands.
Table 2.1. Useful Command-line Editing Shortcuts
Shortcut Description
Ctrl+A Jump to the beginning of the command line.
Ctrl+E Jump to the end of the command line.
Ctrl+U Clear from the cursor to the beginning of the command line.
Ctrl+K Clear from the cursor to the end of the command line.
Ctrl+LeftArrow Jump to the beginning of the previous word on the command line.
Chapter 3. Manage Files from the Command Line
Describe Linux File System Hierarchy Concepts
Quiz: Describe Linux File System Hierarchy Concepts
Specify Files by Name
Quiz: Specify Files by Name
Manage Files with Command-line Tools
Guided Exercise: Manage Files with Command-line Tools
Make Links Between Files
Guided Exercise: Make Links Between Files
Match File Names with Shell Expansions
Quiz: Match File Names with Shell Expansions
Lab: Manage Files from the Command Line
Summary
Abstract
Goal Copy, move, create, delete, and organize files from the Bash shell.
Objectives
Describe how Linux organizes files, and the purposes of various directories in the file-system hierarchy.
Specify the absolute location and relative location of files to the current working directory, determine and change the working directory, and list the contents of directories.
Create, copy, move, and remove files and directories.
Create multiple file name references to the same file with hard links and symbolic (or "soft") links.
Efficiently run commands that affect many files by using pattern matching features of the Bash shell.
Sections
Describe Linux File System Hierarchy Concepts (and Quiz)
Specify Files by Name (and Quiz)
Manage Files with Command-line Tools (and Guided Exercise)
Make Links Between Files (and Guided Exercise)
Match File Names with Shell Expansions (and Quiz)
Lab
Manage Files from the Command Line
Describe Linux File System Hierarchy Concepts
Objectives
Describe how Linux organizes files, and the purposes of various directories in the file-system hierarchy.
The File-system Hierarchy
The Linux system stores all files on file systems, which are organized into a single inverted tree known as a file-system hierarchy. This hierarchy is an inverted tree because the tree root is at the top, and the branches of directories and subdirectories stretch below the root.
Figure 3.1: Significant file-system directories in Red Hat Enterprise Linux 9
The / directory is the root directory at the top of the file-system hierarchy. The / character is also used as a directory separator in file names. For example, if etc is a subdirectory of the / directory, then refer to that directory as /etc. Likewise, if the /etc directory contains a file that is named issue, then refer to that file as /etc/issue.
Subdirectories of / are used for standardized purposes to organize files by type and purpose to make it easier to find files. For example, in the root directory, the /boot subdirectory is used for storing files to boot the system.
Note
The following terms help to describe file-system directory contents:
Static content remains unchanged until explicitly edited or reconfigured.
Dynamic or variable content might be modified or appended by active processes.
Persistent content remains after a reboot, such as configuration settings.
Runtime content from a process or from the system is deleted on reboot.
The following table lists some of the significant directories on the system by name and purpose.
Table 3.1. Significant Red Hat Enterprise Linux Directories
Location Purpose
/boot Files to start the boot process.
/dev Special device files that the system uses to access hardware.
/etc System-specific configuration files.
/home Home directory, where regular users store their data and configuration files.
/root Home directory for the administrative superuser, root.
/run Runtime data for processes that started since the last boot. This data includes process ID files and lock files. The contents of this directory are re-created on reboot. This directory consolidates the /var/run and /var/lock directories from earlier versions of Red Hat Enterprise Linux.
/tmp A world-writable space for temporary files. Files that are not accessed, changed, or modified for 10 days are deleted from this directory automatically. The /var/tmp directory is also a temporary directory, in which files that are not accessed, changed, or modified in more than 30 days are deleted automatically.
/usr Installed software, shared libraries, including files, and read-only program data. Significant subdirectories in the /usr directory include the following commands:
/usr/bin: User commands
/usr/sbin: System administration commands
/usr/local: Locally customized software
/var System-specific variable data should persist between boots. Files that dynamically change, such as databases, cache directories, log files, printer-spooled documents, and website content, might be found under /var.
Important
In Red Hat Enterprise Linux 7 and later, four older directories in / have identical contents to their counterparts in /usr:
/bin and /usr/bin
/sbin and /usr/sbin
/lib and /usr/lib
/lib64 and /usr/lib64
Earlier versions of Red Hat Enterprise Linux had distinct directories with different sets of files. In Red Hat Enterprise Linux 7 and later, the directories in / are symbolic links to the matching directories in /usr.
Make Links Between Files
Objectives
Make multiple file names reference the same file with hard links and symbolic (or "soft") links.
Manage Links Between Files
You can create multiple file names that point to the same file. These file names are called links.
You can create two types of links: a hard link, or a symbolic link (sometimes called a soft link). Each way has its advantages and disadvantages.
Create Hard Links
Every file starts with a single hard link, from its initial name to the data on the file system. When you create a hard link to a file, you create another name that points to that same data. The new hard link acts exactly like the original file name. After the link is created, you cannot tell the difference between the new hard link and the original name of the file.
You can determine whether a file has multiple hard links by using the ls -l command. One item that it reports is each file's link count, the number of hard links that the file has. In the next example, the link count of the newfile.txt file is 1. It has exactly one absolute path, which is the /home/user/newfile.txt location.
[user@host ~]$ pwd
/home/user
[user@host ~]$ ls -l newfile.txt
-rw-r--r--. 1 user user 0 Mar 11 19:19 newfile.txt
You can use the ln command to create a hard link (another file name) that points to an existing file. The command needs at least two arguments: a path to the existing file, and the path to the hard link that you want to create.
The following example creates a hard link called newfile-hlink2.txt for the existing newfile.txt file in the /tmp directory.
[user@host ~]$ ln newfile.txt /tmp/newfile-hlink2.txt
[user@host ~]$ ls -l newfile.txt /tmp/newfile-hlink2.txt
-rw-rw-r--. 2 user user 12 Mar 11 19:19 newfile.txt
-rw-rw-r--. 2 user user 12 Mar 11 19:19 /tmp/newfile-hlink2.txt
To determine whether two files are hard linked, use the ls command -i option to list each file's inode number. If the files are on the same file system and their inode numbers are the same, then the files are hard links that point to the same data file content.
[user@host ~]$ ls -il newfile.txt /tmp/newfile-hlink2.txt
8924107 -rw-rw-r--. 2 user user 12 Mar 11 19:19 newfile.txt
8924107 -rw-rw-r--. 2 user user 12 Mar 11 19:19 /tmp/newfile-hlink2.txt
Important
Hard links that reference the same file share the inode structure with the link count, access permissions, user and group ownership, time stamps, and file content. When that information is changed for one hard link, then the other hard links for the same file also show the new information. This behavior is because each hard link points to the same data on the storage device.
Even if the original file is deleted, you can still access the contents of the file provided that at least one other hard link exists. Data is deleted from storage only when the last hard link is deleted, which makes the file contents unreferenced by any hard link.
[user@host ~]$ rm -f newfile.txt
[user@host ~]$ ls -l /tmp/newfile-hlink2.txt
-rw-rw-r--. 1 user user 12 Mar 11 19:19 /tmp/newfile-hlink2.txt
[user@host ~]$ cat /tmp/newfile-hlink2.txt
Hello World
Limitations of Hard Links
Hard links have some limitations. First, you can use hard links only with regular files. You cannot use the ln command to create a hard link to a directory or special file.
Second, you can use hard links only if both files are on the same file system. The file-system hierarchy can be composed of multiple storage devices. Depending on the configuration of your system, when you change into a new directory, that directory and its contents might be stored on a different file system.
You can use the df command to list the directories that are on different file systems. For example, you might see the following output:
[user@host ~]$ df
Filesystem 1K-blocks Used Available Use% Mounted on
devtmpfs 886788 0 886788 0% /dev
tmpfs 902108 0 902108 0% /dev/shm
tmpfs 902108 8696 893412 1% /run
tmpfs 902108 0 902108 0% /sys/fs/cgroup
/dev/mapper/rhel_rhel9--root 10258432 1630460 8627972 16% /
/dev/sda1 1038336 167128 871208 17% /boot
tmpfs 180420 0 180420 0% /run/user/1000
Files in two different "Mounted on" directories and their subdirectories are on different file systems. So, in the system in this example, you can create a hard link between the /var/tmp/link1 and /home/user/file files, because they are both subdirectories of the / directory but not of any other directory on the list. However, you cannot create a hard link between the /boot/test/badlink and /home/user/file files. The first file is in a subdirectory of the /boot directory (on the "Mounted on" list) and it is in the /dev/sda1 file system. The second file is in the /dev/mapper/rhel_rhel9—root file system.
Create Symbolic Links
The ln command -s option creates a symbolic link, which is also called a "soft link". A symbolic link is not a regular file, but a special type of file that points to an existing file or directory.
Symbolic links have some advantages over hard links:
Symbolic links can link two files on different file systems.
Symbolic links can point to a directory or special file, not just to a regular file.
In the following example, the ln -s command creates a symbolic link for the /home/user/newfile-link2.txt file. The name for the symbolic link is /tmp/newfile-symlink.txt.
[user@host ~]$ ln -s /home/user/newfile-link2.txt /tmp/newfile-symlink.txt
[user@host ~]$ ls -l newfile-link2.txt /tmp/newfile-symlink.txt
-rw-rw-r--. 1 user user 12 Mar 11 19:19 newfile-link2.txt
lrwxrwxrwx. 1 user user 11 Mar 11 20:59 /tmp/newfile-symlink.txt -> /home/user/newfile-link2.txt
[user@host ~]$ cat /tmp/newfile-symlink.txt
Symbolic Hello World
In the preceding example, the first character of the long listing for the /tmp/newfile-symlink.txt file is l (letter l) instead of -. This character indicates that the file is a symbolic link and not a regular file.
When the original regular file is deleted, the symbolic link still points to the file but the target is gone. A symbolic link that points to a missing file is called a "dangling symbolic link".
[user@host ~]$ rm -f newfile-link2.txt
[user@host ~]$ ls -l /tmp/newfile-symlink.txt
lrwxrwxrwx. 1 user user 11 Mar 11 20:59 /tmp/newfile-symlink.txt -> /home/user/newfile-link2.txt
[user@host ~]$ cat /tmp/newfile-symlink.txt
cat: /tmp/newfile-symlink.txt: No such file or directory
Important
One side-effect of the dangling symbolic link in the preceding example is that if you create a file with the same name as the deleted file (/home/user/newfile-link2.txt), then the symbolic link is no longer "dangling" and points to the new file. Hard links do not work in this way. If you delete a hard link and then use normal tools (rather than ln) to create a file with the same name, then the new file is not linked to the old file. Consider the following way to compare hard links and symbolic links, to understand how they work:
A hard link points a name to data on a storage device.
A symbolic link points a name to another name, which points to data on a storage device.
A symbolic link can point to a directory. The symbolic link then acts like the directory. If you use cd to change to the symbolic link, then the current working directory becomes the linked directory. Some tools might track that you followed a symbolic link to get there. For example, by default, cd updates your current working directory by using the name of the symbolic link rather than the name of the actual directory. If you want to update the current working directory by using the name of the actual directory, then you can use the -P option.
The following example creates a symbolic link called /home/user/configfiles that points to the /etc directory.
[user@host ~]$ ln -s /etc /home/user/configfiles
[user@host ~]$ cd /home/user/configfiles
[user@host configfiles]$ pwd
/home/user/configfiles
[user@host configfiles]$ cd -P /home/user/configfiles
[user@host etc]$ pwd
/etc
Match File Names with Shell Expansions
Objectives
Efficiently run commands that affect many files by using pattern matching features of the Bash shell.
Command-line Expansions
When you type a command at the Bash shell prompt, the shell processes that command line through multiple expansions before running it. You can use these shell expansions to perform complex tasks that would otherwise be difficult or impossible.
Following are the main expansions that Bash shell performs:
Brace expansion, which can generate multiple strings of characters
Tilde expansion, which expand to a path to a user home directory
Variable expansion, which replaces text with the value that is stored in a shell variable
Command substitution, which replaces text with the output of a command
Pathname expansion, which helps to select one or more files by pattern matching
Pathname expansion, historically called globbing, is one of the most useful features of Bash. With this feature, it is easier to manage many files. By using metacharacters that "expand" to match the file and path names that you are looking for, commands can act on a focused set of files at once.
Pathname Expansion and Pattern Matching
Pathname expansion expands a pattern of special characters that represent wild cards or classes of characters into a list of file names that match the pattern. Before the shell runs your command, it replaces the pattern with the list of file names that matched. If the pattern does not match anything, then the shell tries to use the pattern as a literal argument for the command that it runs. The following table lists common metacharacters and pattern classes that are used for pattern matching.
Table 3.2. Table of Metacharacters and Matches
Pattern Matches
* Any string of zero or more characters
? Any single character
[abc…] Any one character in the enclosed class (between the square brackets)
[!abc…] Any one character not in the enclosed class
[^abc…] Any one character not in the enclosed class
[[:alpha:]] Any alphabetic character
[[:lower:]] Any lowercase character
[[:upper:]] Any uppercase character
[[:alnum:]] Any alphabetic character or digit
[[:punct:]] Any printable character that is not a space or alphanumeric
[[:digit:]] Any single digit from 0 to 9
[[:space:]] Any single white space character, which might include tabs, newlines, carriage returns, form feeds, or spaces
For the next example, imagine that you ran the following commands to create some sample files:
[user@host ~]$ mkdir glob; cd glob
[user@host glob]$ touch alfa bravo charlie delta echo able baker cast dog easy
[user@host glob]$ ls
able alfa baker bravo cast charlie delta dog easy echo
[user@host glob]$
In the next example, the first two commands use simple pattern matches with the asterisk (*) to match all the file names that start with "a" and all the file names that contain an "a", respectively. The third command uses the asterisk and square brackets to match all the file names that start with "a" or "c".
[user@host glob]$ ls a*
able alfa
[user@host glob]$ ls *a*
able alfa baker bravo cast charlie delta easy
[user@host glob]$ ls [ac]*
able alfa cast charlie
The next example also uses question mark (?) characters to match some of those file names. The two commands match only file names with four and five characters in length, respectively.
[user@host glob]$ ls ????
able cast easy echo
[user@host glob]$ ls ?????
baker bravo delta
Brace Expansion
Brace expansion is used to generate discretionary strings of characters. Braces contain a comma-separated list of strings, or a sequence expression. The result includes the text that precedes or follows the brace definition. Brace expansions might be nested, one inside another. You can also use double-dot syntax (..), which expands to a sequence. For example, the {m..p} double-dot syntax inside braces expands to m n o p.
[user@host glob]$ echo {Sunday,Monday,Tuesday,Wednesday}.log
Sunday.log Monday.log Tuesday.log Wednesday.log
[user@host glob]$ echo file{1..3}.txt
file1.txt file2.txt file3.txt
[user@host glob]$ echo file{a..c}.txt
filea.txt fileb.txt filec.txt
[user@host glob]$ echo file{a,b}{1,2}.txt
filea1.txt filea2.txt fileb1.txt fileb2.txt
[user@host glob]$ echo file{a{1,2},b,c}.txt
filea1.txt filea2.txt fileb.txt filec.txt
A practical use of brace expansion is to create multiple files or directories.
[user@host glob]$ mkdir ../RHEL{7,8,9}
[user@host glob]$ ls ../RHEL*
RHEL7 RHEL8 RHEL9
Tilde Expansion
The tilde character (~), matches the current user's home directory. If it starts with a string of characters other than a slash (/), then the shell interprets the string up to that slash as a username, if one matches, and replaces the string with the absolute path to that user's home directory. If no username matches, then the shell uses an actual tilde followed by the string of characters.
In the following example, the echo command is used to display the value of the tilde character. You can also use the echo command to display the values of brace and variable expansion characters, and others.
[user@host glob]$ echo ~root
/root
[user@host glob]$ echo ~user
/home/user
[user@host glob]$ echo ~/glob
/home/user/glob
[user@host glob]$ echo ~nonexistinguser
~nonexistinguser
Variable Expansion
A variable acts like a named container that stores a value in memory. Variables simplify accessing and modifying the stored data either from the command line or within a shell script.
You can assign data as a value to a variable with the following syntax:
[user@host ~]$ VARIABLENAME=value
You can use variable expansion to convert the variable name to its value on the command line. If a string starts with a dollar sign ($), then the shell tries to use the rest of that string as a variable name and to replace it with the variable value.
[user@host ~]$ USERNAME=operator
[user@host ~]$ echo $USERNAME
operator
To prevent mistakes due to other shell expansions, you can put the name of the variable in curly braces, for example ${VARIABLENAME}.
[user@host ~]$ USERNAME=operator
[user@host ~]$ echo ${USERNAME}
operator
Variable names can contain only letters (uppercase and lowercase), numbers, and underscores. Variable names are case-sensitive and cannot start with a number.
Command Substitution
Command substitution enables the output of a command to replace the command itself on the command line. Command substitution occurs when you enclose a command in parentheses and precede it by a dollar sign ($). The $(command) form can nest multiple command expansions inside each other.
[user@host glob]$ echo Today is $(date +%A).
Today is Wednesday.
[user@host glob]$ echo The time is $(date +%M) minutes past $(date +%l%p).
The time is 26 minutes past 11AM.
Note
An earlier form of command substitution uses backticks: `command`. Although the Bash shell still accepts this format, try to avoid it because it is easy to visually confuse backticks with single quotation marks, and backticks cannot be nested.
Protecting Arguments from Expansion
Many characters have a special meaning in the Bash shell. To prevent shell expansions on parts of your command line, you can quote and escape characters and strings.
The backslash (\) is an escape character in the Bash shell. It protects the following character from expansion.
[user@host glob]$ echo The value of $HOME is your home directory.
The value of /home/user is your home directory.
[user@host glob]$ echo The value of \$HOME is your home directory.
The value of $HOME is your home directory.
In the preceding example, with the dollar sign protected from expansion, Bash treats it as a regular character, without variable expansion on $HOME.
To protect longer character strings, you can use single quotation marks (') or double quotation marks (") to enclose strings. They have slightly different effects. Single quotation marks stop all shell expansion. Double quotation marks stop most shell expansion.
Double quotation marks suppress special characters other than the dollar sign ($), backslash (\), backtick (`), and exclamation point (!) from operating inside the quoted text. Double quotation marks block pathname expansion, but still allow command substitution and variable expansion to occur.
[user@host glob]$ myhost=$(hostname -s); echo $myhost
host
[user@host glob]$ echo "***** hostname is ${myhost} *****"
***** hostname is host *****
Use single quotation marks to interpret all text between the quotes literally.
[user@host glob]$ echo "Will variable $myhost evaluate to $(hostname -s)?"
Will variable host evaluate to host?
[user@host glob]$ echo 'Will variable $myhost evaluate to $(hostname -s)?'
Will variable $myhost evaluate to $(hostname -s)?
Important
It is easy to confuse the single quotation mark ( ' ) and the command substitution backtick ( ` ), on both the screen and the keyboard. The use of one when you mean to use the other leads to unexpected shell behavior.
Ctrl+RightArrow Jump to the end of the next word on the command line.
Ctrl+R Search the history list of commands for a pattern.
Command shell dasar Linux Redhat
Nana Permana | Berbagi Baik
0
Posting Komentar