Linux bash .sh 脚本基础

203 阅读1分钟

脚本执行器 bash || sh === dash

Ubuntu继承自Debian,Debian曾经采用/bin/bash,后改为/bin/dash === /bin/sh,目的使用更少的磁盘空间、提供较少的功能、获取更快的速度。

但是后来经过shell脚本测试存在运行问题。因为原先在bash shell下可以运行的shell script (shell 脚本),在/bin/sh下还是会出现一些意想不到的问题,不是100%的兼用。

首行标记为#!/bin/sh的脚本不应使用任何POSIX没有规定的特性 (如let等命令, 但#!/bin/bash可以)。

sh 遵循POSIX规范:“当某行代码出错时,不继续往下解释”。

bash 就算出错,也会继续向下执行。

1.文件头声明 指定运行环境

#! 是特殊的表示符,其后面跟的是此解释此脚本的shell的路径 /bin/perl /bin/awk /bin/sed /bin/echo /bin/csh /bin/bash /bin/sh ...

#!/bin/bash

2-1.保存文件 并给与运行权限

chmod +x script.sh # 这样才能用./script.sh 来运行

2-2.显式调用 不需要给文件 chmod +x 运行权限

sh script.sh
bash script.sh

变量

echo "由用户输入变量值 foo: "
read foo
echo "用户定义值: $foo"

a=123
echo "test ${a}sdf"
echo $a

foo=asdf
foo="fff asdf" === fff asdf
foo=`echo 123` === 123

环境变量

~ # 当前用户主目录 /home/ubuntu
echo ~ # /home/ubuntu
echo `echo ~/test` # /home/ubuntu/test

echo "~/test" # ~/test
echo ~"/test" # ~/test

echo "`date`" # Sun Feb 14 19:24:04     2021
echo '`date`' # `date` 单引号内不解释为命令