Shell Base $ (CD ' dirname $;p wd)

Source: Internet
Author: User
Tags function definition

$ CD ' DirName $ ' and some special usages of pwd%/* shell variables in the command line state simply execute $ CD ' DirName $ ' is meaningless. Because he returns the "." of the current path.
This command, written in a script file, returns the directory where the script file is placed, and can be used to locate the relative location of the program to be run (except for absolute locations).
The new test.sh content under/home/admin/test/is as follows:
    1. CD ' DirName $ '
    2. Echo ' pwd '
Then return to/home/admin/to execute
    1. SH test/test.sh
Operation Result:
    1. /home/admin/test
This allows you to know the location of the files deployed with the script, as long as you know the relative location can be based on this directory to locate, and can not care about the absolute location. This increases the portability of the script and can be executed on any server, if it is a deployment script. Some special usages of pwd%/* shell variables

Bash Usage Basics

About commands and command types

For use of the command bash uses the hash table to speed up the next lookup, to add a frequently used command, you can use hash cmd
When you execute a command, bash executes the same name command found in the path in the following type order: Alias keywords function built-in command executable file or script
When bash executes an instruction entered by the user, the first thing to do is to determine the type of command, and you can use type cmd to see if the cmd is a type.
The Enable command is used to decide whether to turn on a built-in command, and you can use enable-n cmd to disable a built-in command.
Command commands are used to remove aliases and function lookups.
The BUILTIN command will only look for built-in commands, ignoring functions and executables.

Job Control: Jobs%1 FG BG kill stop etc.
Alias: Alias dir= ' dir-l ' Unalisa dir
Operating directory stack: dirs pushd popd
File name substitution: dir d[1-3] ls. bash{rc,profile} supports [] a collection of numbers and {} Pairs of strings

Variable
Variable declaration: Declare-a array-F function-I integer-R read-only-X export variable
Local variables are only valid in the shell that they declare, and read-only variables cannot be modified unless their properties are re-declared
Common environment variables:
Bash_version dirstack euid EDITOR GROUPS histfile histsize HOME LANG PWD oldpwd PATH
PPID ps1-4 RANDOM SHELL UID
Export var = value-f The exported variable is function-n shifts global to local variable-p only prints exported variables
Non-read-only variables can be cleared by unset,

Variable substitution
${var:-word} If the variable var is already set and is not empty, the result is a value of Var, otherwise the result is word
${var:=word} If the variable var is already set and is not empty, the result is a value of Var, otherwise set Var to Word
${var:+word} If the variable var is already set and is not empty, set the value of Var to word;
${var:?word} If the variable var is already set and is not empty, replace it with Word, or exit the shell.
${VAR:N} is replaced with a substring starting from n
${var:n:len} with substrings starting from N long len
Variable extension

${var%pattern} removes the minimum matching suffix echo ${pwd%/*} shows the current parent directory path
${var%%pattern} remove the maximum matching suffix
${var#pattern} Remove the minimum matching prefix
${var# #pattern} Remove the maximum matching prefix echo ${pwd##*/} Displays the current directory name
${#var} to be replaced by the number of variable characters
Special variables
$ current Shell's PID
? Exit status of the previous command
! PID of the previous work performed in the background

Read user input
Read input from the terminal to the built-in variable reply
Read var is stored in Var from terminal reading input
Read first. Last read multiple variables from the terminal to deposit, if more input, then the final variable becomes a string containing multiple values
Read-a array reads multiple values from the terminal into the array
Read-p pmtstring var outputs the cue string to the terminal and reads input into Var
Read-r line reads a row and allows/

Variable type conversions
If the variable is not determined by the type at the time of declaration, the variable can dynamically convert the type according to the assignment, but if the variable type is determined at the time of Declaration, the assignment to a different type will result in the loss or error of the original data. Unless the type is re-declared.
For variables of integer type, the algorithm extension is supported on the command line, such as Num=3*4, which supports "" and does not support spaces.
In-process

VAR=16#ABC var is 16 binary number ABC

Output
printf "The number is%.2f/n" 100
Echo-ne "hello/nworld/n"-e means that escape characters need to be parsed,-n means no line breaks are added automatically


Position parameters
$1-0 ${10}
$# Evaluation Position parameter number
$* evaluation of all positional parameters
"$*"
[Email protected]
"[Email protected]"

Reference
() command group, creating child shell execution
{} command group, do not create child shell
' Protect all meta characters from being parsed, want to print ', must be enclosed in double quotes, or use/escape
"" only allows variable and command substitution to protect the remaining metacharacters from being parsed

Command substitution
' cmd '
$ (CMD)
Both result in a string, and if you add "", the newline is left, otherwise the line break is lost.

Mathematical expression Extension
$[Exp]
$ ((exp))

F

Array

Declare-a array= (item1 item2 ...)
Array element reference ${array[i]}
Referencing the entire array ${array[*]}
unset array

function definition
function f ()
{
Cmd;cmd;
}

I/O redirection
Find. Name/*.C print > Foundit 2>&1

Command-line arguments

The set can be used to set positional parameters, use set--Clears all positional parameters
The difference between $* and [email protected] is only "", when $* is placed inside, the parameter table becomes a single string, and when [email protected] is placed inside, each parameter is enclosed in quotation marks.

An expression

Evaluate an expression

Expr $[3+4] $[3+4] $ ((3+4))

Let arithmetic extension
Let I=i+1 supports any operator of type C, but only supports the shaping number operation
Bash does not support fractional runs, so it needs to be run in either BC or awk before returning the results. Since bash has no floating-point type, decimals are represented as strings.

To test an expression
Tests can be using test or simply [EXPR1 CMP EXPR2], and the results are stored in a variable, i.e. test and [] equivalent
String Test
[STR1 = str2] str1 same as str2 or = =
[Str1! = str2] St1 is not the same as str2
[STR] STR non-null
[-Z str] STR has a length of 0
[-N str] STR is not 0 in length
[-l STR] STR length
[Str1-a str2] and
-O or
! Not
Compound condition Test
[[P1 && P2]] P1 and P2 are true
[[P1 | | p2]]
[[!P2]]
integer Test
[Num1-eq num2]
[Numb1-ne num2]
GT GE Lt le
File Properties Test
[file1 NT File2] file 1 newer than file 2
[File1 ot File2]
[File1 EF File2]
[-D file] file as directory
-b-c-p-l-S block file, character file, pipeline, link, socket
-e-f file exists, regular file
-G file exists and has a valid GID
-O file exists and has a valid UID
-G Set GID
-K Set Stick bit
-r-w-X Files are readable, writable, executable
-S file non-0
-T file FD opens in terminal
-U setuid bit setting

The test expression can be equivalent to the let's operation extension and the C-type operation extension in (()), which may be easier to understand, c-like.

Condition control
if command
Then
Command
Command
Fi

if test expression
Then
Command
Fi

If [string/numeric expression] Then
Command
Fi

if [[string expression]] Then
Command
Fi

if ((numeric expression))


if command
Then
Command (s)
Else
Command (s)
Fi

if command
Then
Command (s)
elif command
Then
Commands (s)
elif command
Then
Command (s)
Else
Command (s)
Fi

Empty command:

Branch Jump
Case variable in
value1)
Command (s)
;;
value2)
Command (s)
;;
*)
Command (s)
;;
Esac

Cycle
For variable in word_list
Do
Command (s)
Done

While condition
Do
Command (s)
Done

Until command
Do
Command (s)
Done

Build a Select for a menu
Select program in ' ls-f ' pwd date
Do
$program
Done

Interrupt loop
Break [n] jumps out of the nth layer loop
Continue [n] continues the nth layer loop

Capture Signal
Signal List

1) SIGHUP 9) SIGKILL SIGCHLD) Sigxfsz
2) SIGINT) SIGUSR1 Sigcont) sigvtalrm
3) Sigquit one) SIGSEGV SIGSTOP) sigprof
4) Sigill) SIGUSR2 SIGTSTP) sigwinch
5) SIGTRAP) sigpipe Sigttin) SIGIO
6) SIGABRT) sigalrm Sigttou) SIGPWR
7) Sigbus SIGTERM) Sigurg
8) SIGFPE Sigstkflt) sigxcpu
Trap ' command; Command ' Signal-number-list
Trap ' command; Command ' signal-name-list processes the signal, and when the signal in the Singal-list is received, execute the commands in the '
Trap Singal reset Signal processing function
Trap lists signal processing has been set

Debug scripts
Bash-x script shows the command execution process, and the result
Bash-v script shows the lines in the scripts
Bash-n script to interpret but not execute

Appendix:

Common commands
Script MyFile saves terminal interaction information in MyFile, using Control+d to exit
Fuser-n TCP 22 Gets the process to open TCP 22
Lsof to get the file opened by the process

From

Http://hi.baidu.com/lianhuxu/blog/item/d059b8b569271ec337d3ca5a.html

http://hi.baidu.com/lixinxinhit/item/9d95758a39324756e63d1909

Shell Base $ (CD ' dirname $;p wd)

Related Article

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.