FAQs about Linux learning: constantly updating

Source: Internet
Author: User

1. Used in shell scripts#Indicates the annotation, which is equivalent to the C Language//Annotations. However, if#Located at the beginning of the first line, and is#!(Shebang) is an exception. It indicates that the script uses the interpreter specified later./bin/shExplain execution

 

$ chmod +x script.sh$ ./script.sh

 

2. Two Methods for executing shell scripts:

$ ./script.sh$ sh ./script.sh

3. Multiple commands separated by semicolons can be entered in one line.

 

$ cd ..;ls -l

4. It only exists in the current shell process.setCommand to display all variables (including local and environment variables) and functions defined in the current Shell Process

 

 

Environment variables are a concept inherent in any process, while local variables are unique to shell. In shell, the definitions and usage of environment variables and local variables are similar. Define or assign a variable in shell:

$ VARNAME=value

Note that no space is allowed on both sides of the equal sign. Otherwise, shell will interpret the equal sign as a command or a command line parameter.

A variable is defined only in the current shell process. It is a local variable and is usedexportYou can use the following command to export local variables as environment variables:

$ export VARNAME=value

You can also do this in two steps:

$ VARNAME=value$ export VARNAME

UseunsetCommand to delete the defined environment variables or local variables.

$ unset VARNAME

If a variable is calledVARNAME, Use${VARNAME}It can represent its value. It can also be used without ambiguity.$VARNAMEIt indicates its value. The following example compares the differences between the two representations:

$ echo $SHELL$ echo $SHELLabc$ echo $SHELL abc$ echo ${SHELL}abc

Note: $ is not required when defining a variable. $ is used when getting the variable value. Different from the C language, shell variables do not need to clearly define the type. In fact, the values of shell variables are strings. For example, we defineVAR=45In factVARThe value is a string.45Rather than an integer. Shell variables do not need to be defined first and then used. If no value is defined for a variable, the value is a null string.

5. Single quotes and double quotation marks in shell scripts are the same as character string delimiters (next section of double quotation marks), rather than character delimiters. Single quotation marks are used to keep the nominal values of all characters in the quotation marks. Even if the \ and carriage return characters in the quotation marks are no exception, the single quotation marks cannot appear in the string. If the quotation marks are not paired, enter the carriage return. Shell will give a prompt to continue the line, asking the user to enclose the quotation marks with a pair. For example:

$ Echo '$ shell' $ shell $ echo 'abc \ (Press ENTER)> de' (Press enter again to end the command) ABC \ de

6. Command replacement: 'or $ ()

It is also a command enclosed by backquotes. Shell executes the command first and then immediately replaces the output result with the current command line. For example, define a variable StoragedateCommand output:

$ DATE=`date`$ echo $DATE

Command replacement can also be used$()Indicates:

$ DATE=$(date)

7,

Double quotation marks are used to keep the literal value of all characters in the quotation marks (carriage return is no exception), except in the following cases:

  • $ You can add a variable name to get the value of the variable.

  • Reverse quotation marks still indicate command replacement

  • \ $ Indicates the nominal value of $

  • \ 'Indicates the literal value'

  • The nominal value of \ "represents ".

  • \ Represents the literal value \

  • In addition to the preceding conditions, the '\' before other characters has no special meaning and only indicates the literal value.

$ Echo "$ shell"/bin/bash $ echo "'date'" Sun APR 20 11:22:06 Cest 2003 $ echo "I 'd say: \ "go for it \" "I 'd say:" Go for it "$ echo" \ "(Press ENTER)>" (Press enter again to end the command) "$ echo "\\"\

8. StartbashThe following script is automatically executed:

  1. Run/etc/profileEvery user in the system needs to execute this script upon logon. If the system administrator wants a setting to take effect for all users, write it in this script.

  2. Search for~/.bash_profile,~/.bash_loginAnd~/.profileFind the first file that exists and is readable for execution. If you want a setting to only take effect for the current user, you can write it in this script./etc/profileThen execute,/etc/profileThe value of some environment variables can be modified in this script, that is, the current user's settings can overwrite the global settings in the system.~/.profileThe STARTUP script isshSpecified,bashIt is required to first search~/.bash_Start script. If not, run~/.profileTo matchshAlways consistent.

  3. By the way~/.bash_logoutScript (if it exists ).

 

9. Test

 

CommandtestOr[You can test whether a condition is true. If the test result is true, the exit status of the command is 0. If the test result is false, the exit status of the command is 1 (note that the logical representation of the C language is exactly the opposite ). For example, test the relationship between two numbers:

$ VAR=2$ test $VAR -gt 1$ echo $?0$ test $VAR -gt 3$ echo $?1$ [ $VAR -gt 3 ]$ echo $?1

Although it looks strange, the left square brackets[It is indeed a command name. The parameters passed to the command should be separated by spaces., For example,$VAR,-gt,3,]Yes[Command, which must be separated by spaces. CommandtestOr[The parameter format is the same,testCommand not required]Parameters. To[For example, the following table lists common test commands:

[ -d DIR ] IfDIRIf a directory exists and is true
[ -f FILE ] IfFILEIf a common file exists, it is true.
[ -z STRING ] IfSTRINGThe length of 0 is true.
[ -n STRING ] IfSTRINGThe non-zero length is true.
[ STRING1 = STRING2 ] True if the two strings are the same
[ STRING1 != STRING2 ] True if the strings are different
[ ARG1 OP ARG2 ] ARG1AndARG2It should be an integer or a variable with an integer value,OPYes-eq(Equal)-ne(Not equal)-lt(Less)-le(Less than or equal)-gt(Greater)-ge(Greater than or equal)

 

Similar to the C language, the test conditions can also be compared with, or, non-logical operations:

Test commands with or, or, not

[ ! EXPR ] EXPRIt can be any test condition in the preceding table ,! Logical Inversion
[ EXPR1 -a EXPR2 ] EXPR1AndEXPR2It can be any test condition in the preceding table,-aRepresentation logic and
[ EXPR1 -o EXPR2 ] EXPR1AndEXPR2It can be any test condition in the preceding table,-oIndicates logic or

 

For example:

$ VAR=abc$ [ -d Desktop -a $VAR = 'abc' ]$ echo $?0

Note: If$VARIf the variable is not defined in advance, the shell expands to an empty string, causing a syntax error in the test condition (expanded[ -d Desktop -a = 'abc' ]As a good shell programming habit, the variable value should always be placed in double quotation marks (expanded[ -d Desktop -a "" = 'abc' ]):

$ unset VAR$ [ -d Desktop -a $VAR = 'abc' ]bash: [: too many arguments$ [ -d Desktop -a "$VAR" = 'abc' ]$ echo $?1

10. Case/esac

caseCommands can be analogous to Cswitch/caseStatement,esacIndicatescaseThe end of the statement block. C LanguagecaseOnly constant expressions of integer or struct type can be matched.caseIt can match the string and wildcard. Each matching branch can have several commands and must end with;. When executing the command, locate the first matching branch and execute the corresponding command, and then jump directlyesacLater, you do not need to usebreakJump out.

#! /bin/shecho "Is it morning? Please answer yes or no."read YES_OR_NOcase "$YES_OR_NO" inyes|y|Yes|YES)  echo "Good Morning!";;[nN]*)  echo "Good Afternoon!";;*)  echo "Sorry, $YES_OR_NO not recognized. Enter yes or no."  exit 1;;esacexit 0

UsecaseThe statement example can be found in the script directory of the system service./etc/init.d. Most scripts in this directory have this form (/etc/apache2For example ):

case $1 instart)...;;stop)...;;reload | force-reload)...;;restart)...*)log_success_msg "Usage: /etc/init.d/apache2 {start|stop|restart|reload|force-reload|start-htcacheclean|stop-htcacheclean}"exit 1;;esac

Startapache2The service command is

$ sudo /etc/init.d/apache2 start

$1Is a special variable. It is automatically set to the first command line parameter during script execution, that isstart, So enterstart)Branch to execute related commands. Similarly, the command line parameter is specifiedstop,reloadOrrestartYou can go to other branches to execute commands related to stopping the service, re-loading the configuration file, or restarting the service.

11. If fi

Similar to C, it is used in Shellif,then,elif,else,fiThese commands implement branch control. This process control statement is essentially composed of several shell commands, as mentioned earlier

if [ -f ~/.bashrc ]; then    . ~/.bashrcfi

There are actually three commands,if [ -f ~/.bashrc ]Is the first,then . ~/.bashrcIs the second,fiIs the third. If the two commands are written in the same line, they must be separated by a; number. If only one command is written in one line, no; number is required. In addition,thenThere is a line break later, but this command is not completed, shell will automatically continue the line, the next line is connectedthenIt is processed as a command. And[Commands are the same. Note that the commands and parameters must be separated by spaces.ifCommand Parameters constitute a sub-command. If the exit status of the sub-command is 0 (true ),thenSubcommand. If exit status is not 0 (false), runelif,elseOrfiSubcommands.ifThe following sub-commands are usually test commands, but can also be other commands. Shell script does not have {} brackets, so usefiIndicatesifThe end of the statement block. See the following example:

#! /bin/shif [ -f /bin/bash ]then echo "/bin/bash is a file"else echo "/bin/bash is NOT a file"fiif :; then echo "always true"; fi

:It is a special command called an empty command. It does not do anything, but the exit status is always true. You can also execute/bin/trueOr/bin/falseReturns the true or false exit status. Let's look at another example:

#! /bin/shecho "Is it morning? Please answer yes or no."read YES_OR_NOif [ "$YES_OR_NO" = "yes" ]; then  echo "Good morning!"elif [ "$YES_OR_NO" = "no" ]; then  echo "Good afternoon!"else  echo "Sorry, $YES_OR_NO not recognized. Enter yes or no."  exit 1fiexit 0

In the above examplereadThe function of the command is to wait for the user to enter a string and store it in a shell variable.

In addition, shell also provides the & | syntax, which is similar to the C language and has the short-circuit feature. Many shell scripts like to write like this:

test "$(whoami)" != 'root' && (echo you are using a non-privileged account; exit 1)

& Is equivalent to "If... then...", and | is equivalent to "if not... then ...". & | Used to connect two commands.-aAnd-oIt is only used to connect two test conditions in a test expression. Pay attention to their differences, for example,

test "$VAR" -gt 1 -a "$VAR" -lt 3

It is equivalent to the following statement:

test "$VAR" -gt 1 && test "$VAR" -lt 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.