Bash Scripting,read与variables(Linux)

在Bash Script中我们写了一系列actions,我们只要运行了此script文件,其中的写入的命令就会自动执行。所以当我们要重复进行某task,将其写成script会方便些。script只是将要执行的命令写成文件,不用人为一个个敲进去,所以执行效果与命令行一个个敲写效果一样。Anything you can run on the command line you may place into a script and they will behave exactly the same. Vice versa, anything you can put into a script, you may run on the command line and again it will perform exactly the same.举例如下:my_script.sh

<pre name="code" class="cpp">#!/bin/bash
# just a demo
echo this is my script demo
#echo output the word after it
ls

 linux中文件可以不用扩展名,但为了方便,script都当作.sh文件。运行结果如下: 

[@entmcnode15] axi2lite_2 $ cat my_script.sh 
#!/bin/bash
# just a demo
echo this is my script demo
#echo output the word after it
ls
[@entmcnode15] axi2lite_2 $ ./my_script.sh
this is my script demo
axi2lite_2.cache  axi2lite_2.sim   my_script.sh           testbench_behav.wcfg
axi2lite_2.data   axi2lite_2.srcs  testbench_behav1.wcfg
axi2lite_2.runs   axi2lite_2.xpr   testbench_behav2.wcfg
[@entmcnode15] axi2lite_2 $ 

解释:

line 1: cat file_name ,显示文件内容,script 文件名是:my_script.sh

line 2到line 6 是script中的内容

line 2: 每个script文件的第一行都是此命令:#!/bin/bash,用来告诉系统所用解析器是bash。 #!后面紧跟的/bin/bash是bash的path。由于有些系统默认解析器就是bash,所以 #!/bin/bash有时可以不写,但为了保险起见此句作为script的第一句。

line 3:#后面的是注释。

line 7:./my_script.sh 就是执行my_script.sh文件。其中,"."表示当前目录,所以 ./my_script.sh 表示执行当前目录中的my_script.sh文件。我们也可以用绝对路径来指定所要执行的script文件,如/axi2lite_2/my_script.sh 即为执行my_script.sh

line8到line11:my_script.sh执行结果

当script建成后,默认我们并没有执行权限,所以需要设置权限:chmod 755 <script>     ,7=> 对应8进制的 111 可读可写可执行,5=> 对应8进制的 101 可读不可写可执行   
  

在script中可以设置用户input:read var,将用户输入传到变量var中,同时read有一些参数配置,常用的有: -p,后面跟' ',单引号内为提示内容,即在terminal中会显示单引号中内容;-s: makes the input silent,即在terminal中不显示输入内容。如:

login.sh

#!/bin/bash
# Ask the user for login details
read -p 'Username: ' uservar
read -sp 'Password: ' passvar
echo
echo Thankyou $uservar we now have your login details
执行结果:

./login.sh
Username: ryan
Password:
Thankyou ryan we now have your login details


variables:A variable is a container for a simple piece of data. 如:name='Ryan'。注意:=两边没有空隙,即数据紧贴在一起。当调用变量时,需要在其名字前加$,如$name

Example:

cat variableexample.sh
#!/bin/bash
# A simple demonstration of variables
# Ryan 5/9/2014 
name=Ryan
echo Hello $name
./variableexample.sh
Hello Ryan


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值