قالب وردپرس درنا توس
Home / Tips and Tricks / 15 special characters that you need to know for Bash

15 special characters that you need to know for Bash



  A Linux terminal full of text on a laptop.

If you want to master the Bash shell on Linux, macOS, or any other UNIX-like system, you must type special characters (such as ~, *, |, and>) critically. We help you decode these cryptic Linux command sequences and become a hieroglyphic hero.

What are special characters?

The Bash shell handles a series of characters in two different ways. When you enter them into the shell, they act as statements or commands, instructing the shell to perform a specific function. Think of them as single-character commands.

Sometimes you just want to print one character and do not need it to act as a magic symbol. There is a way to use a character to represent yourself rather than its special function.

We show you which characters are special or metacharacters and how you can use them functionally and literally.

~ Home Directory

The tilde (~) is the abbreviation for your home directory. This means that you do not need to enter the full path to your home directory in the commands. Wherever you are in the file system, you can use this command to change to your home directory:

  cd ~ 

  The

You can also use this command with relative paths. For example, if you are in the file system that is not in your home folder and you want to change to the archive directory in your working directory use the tilde:

  cd ~ / work / archive 

  The

. Current Directory

One dot (.) Represents the current directory. You can see it in directory listing if you use the option -a (all) with ls .

  ls -a 

<img class = "alignnone wp-image-439259 size-full" data-pagespeed-lazy-src = "https://www.howtogeek.com/wp-content/uploads/2019 /09/x3.png.pagespeed.gp+jp+jw+pj+ws+js+rj+rp+rw+ri+cp+md.ic.ItG1OfFov8.png "alt =" You can also use the dot in commands to represent the path to your current directory, for example, if you want to run a script from the current directory, call it as follows:

  ./ script.sh 

This tells Bash to look in the current directory file so that the directories in your path are not searched for matching executables or scripts.

 The

.. Parent directory

The double dot or "double dot" (..) represents the parent directory of your current one. You can use this command to save in the directory tree ne level to go up.

  cd .. 

 The

You can also use this command with relative paths; If you like, go up one level in the directory structure and enter another directory there.

You can also use this technique to quickly move to a directory that is in the directory tree at the same level as the current one. You jump one level higher and then one level deeper into another directory.

  cd ../gc_help[19659020[19459038[The"cd/gc_help"commandinaterminalwindow"Width="646"height="77"src="/pagespeed_static/1JiBnMqyl6Sgif"onload="pagespeedlazyLoadImagesloadIfVisibleAndMaybeBeacon(this);"onerror="thisonerror=null;pagespeedlazyLoadImagesloadIfVisibleAndMaybeBeacon(this);"/>

/ Path Directory Separator

You can use a forward slash (/) - often referred to as a slash - used to separate directories in a pathname.

  ls ~ / work / archive 

 The

slash represents the shortest possible directory path If everything in the Linux directory structure begins in the root directory, you can use this command to quickly switch to the root directory:

  cd / 

 The

# Comment or Trim Strings [19659004] In In most cases, use the hash or pound sign (#) to tell the shell that the following comment is a comment that should not be edited. You can use it in shell scripts and, less meaningfully, in the command line.

  # This is ignored by the bash shell 

 The

However, it is not really ignored because it was added to your command history.

You can also use the hash to truncate a string variable and remove text at the beginning. This command creates a string variable named this_string .

In this example, we assign the variable "Dave Geek!" To the variable. To.

  this_string = "Dave Geek!" 

]

This command uses echo to print the words "how-to" in the terminal window. A parameter extension retrieves the value stored in the string variable. As we append the hash and the text "Dave," that part of the string is truncated before being passed to echo .

  echo how-to $ {this_string # dave} 

] To

This does not change the value stored in the string variable. It only affects what was sent to echo . We can use echo to re-print the value of the string variable and verify the following:

  echo $ this_string 

 The

? Single-character wildcard

The bash shell supports three wildcards, one of which is the question mark (?). You use wildcards to replace characters in filename templates. A filename that contains a wildcard character forms a template that corresponds to not just one but a set of filenames.

The question mark as a wildcard sign stands for exactly one character . Consider the following file name template:

  ls badge? .Txt 

This means "Lists all files with a name beginning with" badge "and followed by a single character before the filename extension."

It matches the following files. Note that some numbers and some letters are after the "badge" part of the file name. The question mark wildcard matches both letters and numbers.

 The

However, this filename template does not match "badge.txt" because the filename does not contain a single character "badge" and the file extension. The question mark wildcard must match a corresponding character in the file name.

You can also use the question mark to search all files with a specified number of characters in the file name. All text files with exactly five characters in the file name are listed here:

  ls ?????. Txt 

 A

* wildcard for string

You can use the asterisk (*) wildcard for any string including without . Consider the following file name template:

  ls badge * 

This matches all of the following matches:

 At

It matches "badge.txt" because the wildcard contains a represents any sequence of characters or no characters.

This command matches any source named file, regardless of the file extension.

  ls source. * 

 A

[] Character Set Wildcard [19659004] As described above, use the question mark to represent any single character and the star any sequence of characters (including any characters)

You can use the square brackets ([]) and the characters to form a wildcard character that contains them. The relevant character in the file name must then match at least one of the characters in the wildcard character set.

In this example, the command is translated into the following: "Any file with the extension" .png ", a file name that starts with" pipes_0 "," And in which the next character either 2, 4 or 6 is. "

  ls badge_0 [246] .txt 

 A

that you can use more than one set of parentheses per filename template:

  ls badge_ [01][789]  .txt [19659017]  An  

You can also include ranges in the character set. The following command selects files numbered 21 through 25 and 31 through 35 in the file name.

  ls badge_ [23][1-5]  .txt 

 An

; Shell Command Separator

You can type as many commands on the command line as you like, as long as you separate them with a semicolon (;). We will do this in the following example:

  ls> count.txt; wc -l count.txt; rm count.txt 

 A count.txt; wc -l count.txt; Command rm count.txt in a terminal window width = "646" height = "122" src = "/pagespeed_static/1.JiBnMqyl6S.gif" onload = "pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon (this);" onerror = "this.onerror = null; pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon (this);" />

Note that the second command executes, even if the first fails, the third, even if the second fails, and so on. [19659005] If you want to pause the execution sequence if a command fails, use a double Et (&&) instead of a semicolon:

  cd ./doesntexist && cp ~ / Documents / reports / *. 

] A

& background process

After typing and closing a command in a terminal window, you return to the command prompt. Usually, this only takes a moment or two. However, if you start another application such as gedit you will not be able to use your terminal window until you close the application.

However, you can start an application as a background process and continue to use the terminal window. Simply add an ampersand to the command line:

  gedit command_address.page & 

 A

Bash shows you the process ID of what was started, and then gives you at the back command line. Then you can continue using your terminal window.

<input redirect

Many Linux commands accept a file as a parameter and obtain its data from that file. Most of these commands can also accept input from a stream. To create a stream, use the left square bracket (<), as shown in the following example, to redirect a file to a command:

  sort <words.txt 

<img class = "alignnone wp-image -439313 size-full "data-pagespeed-lazy-src =" https://www.howtogeek.com/wp-content/uploads/2019/09/x23.png.pagespeed.gp+jp+jw+pj+ ws + js + rj + rp + rw + ri + cp + md.ic.5v6pdWRPSW.png "alt =" A "sorting < words.txt" command in a terminal window." width="646" height="197" src="/pagespeed_static/1.JiBnMqyl6S.gif" onload="pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);" onerror="this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);"/>

When input is redirected to a command, it may behave differently than when it reads a named file.

If we use wc to count the words, lines, and characters in a file, first the values ​​and then the file name are printed. If we redirect the contents of the file to wc the same numeric values ​​will be output, but the name of the file from which the data originates will be unknown. A file name can not be printed.

Here are some examples of using wc :

  wc words.txt 
  wc <words.txt 

 A ]

> Output redirection [19659004] Use the square brackets (>) to redirect the output of a command (usually to a file). Here is an example:

  ls> files.txt 
  cat files.txt 

 A files.txt "command in a terminal window." width = "646" height = "382" src = "/pagespeed_static/1.JiBnMqyl6S.gif" onload = "pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon (this);" onerror = "this.onerror = null; pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon (this);" />

The output redirect can also redirect error messages when using a digit (in our example 2) with > [19459009verwenden]. Here's how it is done:

  wc doesntexist.txt 2> errors.txt 
  cat errors.txt 

 A error.txt "command in a terminal window." width = "646" height = "122" src = "/pagespeed_static/1.JiBnMqyl6S.gif" onload = "pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon (this);" onerror = "this.onerror = null; pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon (this);" />

RELATED: What are stdin, stdout, and stderr on linux? 19659007] | Pipe

A "pipe" chains commands together. It takes the output from one command and passes it as input to the next one. The number of pipe commands (the length of the chain) is arbitrary.

Here we use cat to enter the contents of the words.txt file in grep . When a line is extracted with a capitalization "C." grep these lines are passed to sort . sort uses the option -r (vice versa) so that the sorted results are displayed in reverse order.

We entered:

  cat words.txt | grep [cC] | sort -r 

 A

! Pipeline logical NOT and gradient operator

The exclamation point (!) Is a logical operator that does NOT mean.

This command line contains two commands:

  [ ! -d ./backup ] && mkdir ./backup[19659130)Thefirstcommandisthetext-enclosedbrackets[196519126] The second command is the text following the double et sign  && . 

The first command uses ! as a logical operator. The square brackets indicate that a test is being performed. The option -d (directory) checks if there is a directory called backup. The second command creates the directory.

Since the two commands are separated by a double ampersand, Bash executes the second command only if the first one succeeds . However, this is the opposite of what we need. If the test for the "backup" directory succeeds, we do not have to create it . And if the test for the backup directory fails, the second command will not be executed and the missing directory will not be created.

Here comes the logical operator ! into play. It acts like a logical NOT. If the test is successful (ie the directory exists), tilts ! that to "NOT successful", which is Bust . Therefore, the second command is not activated .

If the directory test fails (ie the directory does not exist), change ! the answer to "NOT failed," which is success . The command to create the missing directory is executed .

This little ! packs a lot of punch when you need it!

To verify the status of To Back Up the Folder, use the command ls and the options -l (long listing) and -d (directory) (see below):

  ls -l -d backup 

 A

You can also execute commands from your command history with the exclamation point. The command history lists your command history and then you enter the number of the command that you have with ! again, as shown below:

! 24 

 A

The following command executes the previous command again:

  !! 

$ Variable expressions

In the bash shell, you create variables for storing values. Some, such as For example, environment variables are always present, and you can access them whenever you open a terminal window. These values ​​include values ​​such as username, home directory, and path.

With echo you can see the value a variable contains - just put the dollar sign ($) in front of the variable name Figure below:

  echo $ USER 
  echo $ HOME [19659103] echo $ PATH 

 An

To create a variable, you must give it a name and specify a value for it to hold. You do not have to use the dollar sign to create a variable. Add $ only if you reference a variable, as in the following example:

  ThisDistro = Ubuntu 
  MyNumber = 2001 
  echo $ ThisDistro 
  echo $ MyNumber [19659017]  On  

Insert curly braces ({}) around the dollar sign and perform a parameter extension to get the value of the variable and allow further transformations of the value.

This creates a variable with a string as shown below:

  MyString = 123456qwerty 

Use the following command to render the string in the terminal window:

  echo $ {MyString} 

To to return the substring from position 6 onwards Use the following command for the entire string (there is a zero offset so that the first position is null):

  echo $ {myString: 6} 

If you want to print a substring, Starting at position zero and using the following command for the next six characters:

  echo $ {myString: 0: 6} 

Use the following command to echo a substring that starts at position four and ends the next four characters contain:

  echo $ {myString: 4: 4} 

 A

Citation of special characters

If you have a special character If you want to use a literal (not special) character, you must tell the bash shell. This is called a quote, and there are three ways to do it.

Enclosing the text in quotation marks ("...") prevents Bash from affecting most of the special characters, and they are only printed. A notable exception, however, is the dollar sign ($). It also acts as a variable expression character so you can include the values ​​of variables in your output.

For example, this command prints the date and time:

  echo "Today is $ (date)" [19659020] If you put the text in single quotation marks (& # 39; ... & # 39;) as shown below , the function of all    special characters terminates: 

  echo & # 39; today is $ (date) & # 39; 

It can use a backslash () to prevent the following character from acting as a special character. This is called "escape" of the character. See the following example:

  echo "Today is  $ (date)" 

 An

Think of special characters as very short commands. Remembering their usage can greatly improve your understanding of the bash shell - and the scripts of others.

RELATED: 37 Important Linux Commands You Should Know




Source link