一、Shell脚本入门
需要的基础:Linux命令
1、创建/opt/shell目录,在其下创建一个简单的shell;
[root@hadoop001 shell]# cat helloworld.sh
#!/bin/bash
echo "www.ruozedata.com"
2、执行shell
[root@hadoop001 shell]# /opt/shell/helloworld.sh
-bash: /opt/shell/helloworld.sh: Permission denied
[root@hadoop001 shell]# ./helloworld.sh
-bash: ./helloworld.sh: Permission denied
[root@hadoop001 shell]# pwd
/opt/shell
//为什么提示command not found呢,因为/opt/shell没有配置环境变量:
[root@hadoop001 shell]# helloworld.sh
-bash: helloworld.sh: command not found
3、赋予执行权限,就能直接执行:
[root@hadoop001 shell]# chmod 654 helloworld.sh
[root@hadoop001 shell]# ./helloworld.sh
www.ruozedata.com
//一般不使用+x命令
[root@hadoop001 shell]# chmod +x helloworld.sh
Shell脚本如何进行Debug?
- 在解释器后面加一个-x,再次进行执行即可。
- [root@hadoop001 shell]# cat helloworld.sh
#!/bin/bash -x
echo “www.ruozedata.com”
1、把bin/bash解释器删除,
[root@hadoop001 shell]# which sh
/bin/sh
2、使用/bin/sh执行:
[root@hadoop001 shell]# /bin/sh helloworld_nohead.sh
www.ruozedata.com
3、调试:
[root@hadoop001 shell]# sh -x helloworld_nohead.sh
+ echo www.ruozedata.com
www.ruozedata.com
总结:
1、开头定义:#/bin/bash
2、 sh -x xxx.sh
如果第一行#!/bin/bash -x,这样会影响结果查看,建议使用sh -x;sh是万能的:
[root@hadoop001 shell]# chmod 644 helloworld.sh
[root@hadoop001 shell]# ll
total 8
-rw-r-xr-- 1 root root 26 Apr 12 15:08 helloworld_nohead.sh
-rw-r--r-- 1 root root 40 Apr 12 14:57 helloworld.sh
[root@hadoop001 shell]# sh helloworld.sh
www.ruozedata.com
[root@hadoop001 shell]# ./helloworld.sh
-bash: ./helloworld.sh: Permission denied
1.1、定义变量和使用
1、静态变量:k=v k="v" 数值和字符串的定义
2、动态变量:k=`v`,v是指linux的命令,定义动态变量的时候等号前后不能有空格
3、引用:$k、${k},只有我们在引用的时候才需要加上$
[root@hadoop001 shell]# cat variable.sh