linux 变量定义

本地变量:用户自定义的变量。

环境变量:用于所有用户变量,用于用户进程前,必须用export命令导出。

位置变量:$0(脚本名),$1-$9:脚本参数。

特定变量:脚本运行时的一些相关信息。

$# 传递到脚本的参数个数
$* 传递到脚本的参数,与位置变量不同,此选项参数可超过9个
$$ 脚本运行时当前进程的ID号,常用作临时变量的后缀,如haison.$$
$! 后台运行的(&)最后一个进程的ID号
$@ 与$#相同,使用时加引号,并在引号中返回参数个数
$- 上一个命令的最后一个参数
$? 最后命令的退出状态,0表示没有错误,其他任何值表明有错误

#!/bin/sh
#VarTest.sh
#To test the variables
USER=haison
echo "Hello,$USER,the output of this script are as follows:"
echo "The script name is :`basename $0`"
echo "The first param of the script is :$1"
echo "The second param of the script is :$2"
echo "The tenth param of the script is :$10"
echo "All the params you input are :$*"
echo "The number of the params you input are:$#"
echo "The process ID for this script is :$$"
echo "The exit status of this script is :$?"

执行:

[root@cdh1 sh]# ./1.sh 1 2 3 4 5 6
Hello,haison,the output of this script are as follows:
The script name is :1.sh
The first param of the script is :1
The second param of the script is :2
The tenth param of the script is :10
All the params you input are :1 2 3 4 5 6
The number of the params you input are:6
The process ID for this script is :537
The exit status of this script is :0

 注意:

引号内使用变量:"Hello,$USER,the"

取文件的名字:"The script name is :`basename $0`",如果直接使用"The script name is :$0"显示文件路径加名字

在shell里“ ` ”意思
命令替换.`command` 结构使字符(`)[译者注:这个字符不是单引号,而是在标准美国键盘上的ESC键下面,在字符1左边,在TAB键上面的那个键,要特别留心]引住的命令(command)执行结果能赋值给一个变量。它也被称为后引号(backquotes)或是斜引号(backticks).
例子:
A=`ls -l`
把ls -l的结果赋给A ls -l 作为命令来执行

原文地址:https://www.cnblogs.com/cxhfuujust/p/7559944.html