shell 执行脚本的 3 种方式

首先把工作目录切换到脚本所在的目录:
该脚本所在的目录为:/home/user
cd /home/user
脚本为:hello_shell.sh
脚本的内容为:
#!/usr/bin/env bash
echo “hello shell”

方法一

sh hello_shell.sh
或者
bash hello_shell.sh
注该该种方式执行不需要为脚本赋予执行权限
-rw-rw-r– hello_shell.sh

方法二

相对路径
./hello_shell.sh
绝对路径
/home/user/hello_shell.sh
该种方式需要为脚本授予可执行权限
chmod 764 hello_shell.sh
-rwxrw-r– hello_shell.sh

方法三

. hello_shell.sh
或者
source hello_shell.sh

注:

前两种方法和第三种方法的区别:
前两种方法执行 shell 脚本时都是在当前 shell 环境下又开了一个子 shell 环境,当脚本执行完后,子 shell 环境立刻就会关闭,而方法三是在当前 shell 环境下执行的。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Shell脚本是一命令行解释器,可以直接执行命令、操作文件等。在实际应用中,运行的Shell脚本往往需要传入参数来控制脚本的行为和逻辑,因此学会Shell脚本传参对于我们写出好的脚本是十分必要的。下面介绍Shell脚本传参的三方式: 1. 位置参数传参: 通过$1、$2、$3...的变量获取传入的参数,其中$0表示脚本的名字。 例如: ``` #!/bin/bash echo "The first parameter is $1 and the second parameter is $2." ``` 执行: ``` ./test.sh hello world ``` 输出: ``` The first parameter is hello and the second parameter is world. ``` 2. 特殊变量传参: Shell脚本还提供了一些特殊变量可以用来获取所传递参数的信息,如传递参数个数的${#}、所有参数组成的${*}和所有参数组成的${@}。 例如: ``` #!/bin/bash echo "There are $# parameters." echo "All parameters are ${*}." echo "All parameters are ${@}." ``` 执行: ``` ./test.sh hello world 123 ``` 输出: ``` There are 3 parameters. All parameters are hello world 123. All parameters are hello world 123. ``` 3. 命令行传参: 在执行Shell脚本时直接通过“sh test.sh 参数1 参数2…”的方式传参。这方式需要注意空格和引号,可以使用双引号保留参数中的空格。 例如: ``` #!/bin/bash echo "The first parameter is $1 and the second parameter is $2." ``` 执行: ``` sh test.sh "hello world" 123 ``` 输出: ``` The first parameter is hello world and the second parameter is 123. ``` 总结:以上三方式Shell脚本传参的常用方法,通过具体的需求来决定选用哪方式,以达到最好的效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值