SHELL 脚本-使用命令行打开常用网站
Shell script
簡單的說, shell script 就像是早期 DOS 年代的批次檔 (.bat) ,最簡單的功能就是將許多指令彙整寫在一起, 讓使用者很輕易的就能夠 one touch 的方法去處理複雜的動作 (執行一個檔案 “shell script” ,就能夠一次執行多個指令)。 而且 shell script 更提供陣列、迴圈、條件與邏輯判斷等重要功能,讓使用者也可以直接以 shell 來撰寫程式,而不必使用類似 C 程式語言等傳統程式撰寫的語法呢!
以上内容来自于鸟哥的私房菜。
由于工作、学习需要频繁地使用可视化界面打开一些界面,时间长了难免会觉得费时费力,想象着:如果能一次性地执行一些操作就好了。因此我便入门了BASH SHELL脚本。下面我将举一些简单的例子说明脚本的便捷之处。
- chrome命令化打开
#!/bin/bash
function cm(){chrome_path="/usr/bin/google-chrome"
if [ ! -x ${chrome_path} ];then echo "can not find chrome, please download it!" return;fi
echo "Which u want to open?"url_lists=( "chrome" "gerrit" "confluence" "jira" "JFrog" "outlook" "nothing")
select name in "${url_lists[@]}"do case $name in "chrome") /usr/bin/google-chrome >/dev/null 2>&1 & break ;; "gerrit") /usr/bin/google-chrome --new-window http://xxx >/dev/null 2>&1 & break ;; "confluence") /usr/bin/google-chrome --new-window http://xxx:xxx >/dev/null 2>&1 & break ;; "jira") /usr/bin/google-chrome --new-window http://xxx:xxx/browse/xxx?filter=-1 >/dev/null 2>&1 & break ;; "JFrog") /usr/bin/google-chrome --new-window http://xxx/ >/dev/null 2>&1 & break ;; "nothing") break ;; "outlook") /usr/bin/google-chrome --new-window https://outlook.xxx.com/ >/dev/null 2>&1 & break ;; *) echo "输入错误,请重新输入" esacdone}首先是#!/bin/bash打头,其名称为Shebang,作用为指定解释器来解读后面的代码。当然你也可以使用#!/usr/bin/env python3或#!/usr/bin/python3再或者用#!/usr/bin/python2同样也是可以的。
其次是一个if语法,不同于c++的if(条件),Shell脚本中使用中括号[]来框柱条件语句,注意:条件语句前后需要有被空格填充,比方说 if [ 你好吗? ]是正确的,而if [你好吗``?``]是有问题的,本人因为这个问题浪费很多时间查语法错误。
-
可以看到条件为
-x ${chrome_path},其中-x表示后面的文件是否是可执行文件,同样的你也可以使用-d判断是否有目录存在,使用-f判断是否有文件存在等等。 -
if[ ]的条件判断后应当增加;then表示进入条件后续需要做什么,这是语法。 -
当
if条件执行完毕后应当用fi结束判断语句
最后是一个select ${var} in ,其为bash script默认的一个语法,作用是可以与用户交互,判断用户的输入,执行对应的代码,其输出形式为:
❯ cmWhich u want to open?1) chrome 2) gerrit 3) confluence 4) jira 5) JFrog 6) outlook 7) nothing?#具体项目为chrome.sh,项目中的其他shell脚本将会在后续的博文中进行阐述。