DirName and Shell common commands

Source: Internet
Author: User
Tags function definition

$ CD ' DirName $ ' and pwd%} display 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

    • $ (CD ' dirname $ '; pwd)

It is meaningless to simply execute $ CD ' DirName $ ' in the command-line state. 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 locates the relative location of the program to be run according to the directory.

    • Declare

+/-: "-" can be used to specify the properties of the variable, "+" is the property of the cancellation variable,-f: Only the function; R: The variable is set to read-only; x: The specified variable becomes an environment variable that can be used by a program other than the shell; i:[setting value] can be a numeric, string, or

The declare command is used to declare and display a shell variable that already exists. Displays all shell variables when the variable Name argument is not supplied. The DECLARE command displays all shell variables and their values without any parameter options. The DECLARE function is the same as the function of the typeset command.

    • If ["$#"-ne "8"]; Then

$# indicates the total number of arguments supplied to the shell script or function;
$ $ represents the first parameter.
-ne means not equal to

Other than that:
Integer comparison
-eq equals, such as: if ["$a"-eq "$b"]
-ne Not equal to, such as: if ["$a"-ne "$b"]
-GT greater than, such as: if ["$a"-gt "$b"]
-ge greater than equals, such as: if ["$a"-ge "$b"]
-lt less than, such as: if ["$a"-lt "$b"]
-le less than equals, such as: if ["$a"-le "$b"]
< less (requires double brackets), such as: (("$a" < "$b")
<= is less than or equal (requires double brackets), such as: (("$a" <= "$b"))
> greater than (requires double brackets), such as: (("$a" > "$b")
>= greater than or equal (requires double brackets), such as: (("$a" >= "$b"))

In addition: $? is a shell variable that represents the exit state of the last command execution. 0 for success, not 0 for failure.

basename command

Syntax: basename string [suffix]

The base file name used to return a string

The basename command reads the string parameter, removes the prefix with the/end and any specified suffix parameters, and writes the remaining base file names to the standard output.

The basename command applies the following rules for creating a base file name:

1 · If the string argument is a//(double slash) or if the string argument contains a slash character, change the string to a single/(slash). Skip steps 2 through 4.

Removes any trailing/characters from the specified string.

2 · If any/characters are left in the string parameter, the prefix of the string is dropped until the last/character is (included).
3 · If you specify the Suffix parameter, and it is the same as the remaining characters in the string, the string is not modified. For example, enter:
# Basename/u/dee/desktop/cns.boo Cns.boo
The result is:
Cns.boo
If the Suffix parameter is specified and it is not the same as all characters in the string, but the suffix of the string is the same, the specified suffix is dropped. For example, enter:
# Basename/u/dee/desktop/cns.boo Boo

The result is:
Cns
The specified suffix cannot be found in the string as error handling.

Example

(1) To display the base name of a shell variable, enter:
BaseName $WORKFILE
This command displays the base name of the value assigned to the shell variable workfile. If the value of the Workfile variable is a/home/jim/program.c file, this command displays PROGRAM.C

# Basename/usr/bin/sort
# sort

(2) to construct a file name that is the same as another file name (except for the suffix), enter:
Ofile= ' basename $. C '. O
This command assigns a value to the parameter ($) on the first location of the Ofile file, but its. c suffix changes to. O. If $ $ is a/home/jim/program.c file, then ofile becomes PROGRAM.O. Because PROGRAM.O is only a basic file name, it identifies the files in the current directory.
Note: ' (accent symbol) specifies command substitution.

DirName command

Description of Use
The dirname command can take the directory portion of a given path (strip non-directory suffix from file name). This command is rarely used directly from the shell command line, and I typically use it in a shell script to get the directory where the script file is located and then switch the current directory over. According to the manual page, "Print NAME with its trailing/component removed; If NAME contains no/' s, Output '. ' (meaning the current directory). "It seems that" taking the directory portion of a given path "does not accurately summarize the purpose of the dirname command. Another command under Linux is basename, which, contrary to dirname, is the part that gets the file name.
Common parameters
No.
Using the example
Example one from the manual page example
[Email protected] ~]# Dirname/usr/bin/sort
/usr/bin
[Email protected] ~]# dirname stdio.h
.
[Email protected] ~]#
Example Two
[Email protected] ~]# Dirname/usr/bin
/usr
[Email protected] ~]# dirname/usr/bin/
/usr

DirName and Shell common commands

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.