tags: Linux Bash Shell Script 2019 年 12 月
BashShell 简介
bash shell 是一个命令解释器,它在操作系统的最外层,负责用户程序与内核进行交互操作的一种接口,将用户输入的命令翻译给操作系统,并将处理后的结果输出至屏幕。
bash shell 的作用 使用 shell 实现对 Linux 系统的大部分管理,例如:文件管理、用户管理、权限管理、磁盘管理、网络管理、软件管理、应用管理……
BashShell 使用
语法
功能模块
Tips
检查文件是否存在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| if [ ! -d ${config_path} ]; then echo ">>> 配置文件${config_path}不存在" exit 0 fi
if [ ! -d "/Top" ]; then mkdir -p /Topfi
folder="/Top" file="/Top/test.txt"
if [ ! -x "$folder"]; then mkdir "$folder" fi
if [ ! -d "$folder"]; then mkdir "$folder" fi
if [ ! -f "$file" ]; then touch "$file" fi
if [ ! -n "$file" ]; then echo "$file 变量为空!" exit 0 fi
if [ "$file1" = "$file2" ]; then echo "$file1 equal $file2" else echo "$file1 not equal $file2" fi
|
检查字符串是否在其中
1 2 3 4 5
| STR='GNU/Linux is an operating system' SUB='Linux' if [[ "$STR" == *"$SUB"* ]]; then echo "It's there." fi
|
https://www.linuxidc.com/Linux/2019-08/159866.htm
检查字符串是否存在文件中
1 2 3 4 5 6 7
| if cat ${bash_path} | grep "source ${out_path}" > /dev/null 2>&1 then continue else echo "source ${out_path}" >> ${bash_path} fi
|
解决 sudo 默认密码
1 2
| sudo_password=qwe123 echo ${sudo_password} | sudo -S sh -c "echo 'ssss' > /root/1.log"
|
读取配置文件 config.ini
配置文件config.ini
1 2 3 4 5
| [CONFIG_NAME] KEY1 = val1 KEY2 = val2 [CONFIG_NAME2] KEY3 = val3
|
配置脚本 build_env.sh
内容,只能 . build_env.sh
执行,否则需要手动su - xxx
使环境变量生效
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| (env) [scfan@fdm ~]$ cat build_env.sh
config_path=config.ini out_path=~/.fdm_profile
bash_path=~/.bash_profile
if [ ! -f ${config_path} ]; then echo ">>> 配置文件${config_path}不存在" exit 0 fi
function read_config(){ IFS="=" while read -r name value do if [ "$name" != "" ] && [ "$value" == "" ] && [[ $name =~ "[" ]] && [[ $name =~ "]" ]]; then echo "# item $name" >> ${out_path} elif [ "$name" != "" ] && [ "$value" != "" ]; then name=`echo $name | awk '$1=$1'` value=`echo $value | awk '$1=$1'` echo "export ${name}=${value}" >> ${out_path} else tmp=0 fi done < ${config_path} }
function set_config(){ if cat ${bash_path} | grep "source ${out_path}" > /dev/null 2>&1 then tmp=0 else echo "source ${out_path}" >> ${bash_path} fi
. ${bash_path} }
function clean_config(){ echo "" > ${out_path} }
clean_config; read_config; set_config;
|
脚本输出结果
1 2 3 4 5
| export KEY1=val1 export KEY2=val2
export KEY3=val3
|
问题记录
sudo pip command not found
1 2 3
| echo "alias sudo='sudo env PATH=$PATH'" >> ~/.bashrc source ~/.bashrc
|
sudo echo Permission denied 权限不够的问题
1 2 3 4
| sudo sh -c 'echo "This is testPage." >> /usr/local/nginx/html/index.html' sudo tee version.txt <<< "要插入内容" echo qwe123 | sudo -S sh -c "echo 'ssss' > /root/1.log"
|