Shell腳本快捷方式或別名對於在很少的按鍵中自動執行重複性任務非常有用。如何創建用於創建新腳本並在編輯器中打開它的shell別名?
「快捷方式」命令的示例的一個示例是take
從zsh
,其確實是mkdir $dir && cd $dir
。
我要讓類似的東西(medit
),這是否:叫medit script.sh
時:
- 創建腳本
- 使得它運行(chmod + x)的
- 與家當線填充它
- 在默認編輯器中打開文件
我可以使用a lias所以我會避免寫一個bash腳本來做到這一點?
Shell腳本快捷方式或別名對於在很少的按鍵中自動執行重複性任務非常有用。如何創建用於創建新腳本並在編輯器中打開它的shell別名?
「快捷方式」命令的示例的一個示例是take
從zsh
,其確實是mkdir $dir && cd $dir
。
我要讓類似的東西(medit
),這是否:叫medit script.sh
時:
我可以使用a lias所以我會避免寫一個bash腳本來做到這一點?
你最好寫一個函數,如:
function medit(){
echo "#!/bin/bash" > "$1"
chmod +x "$1"
if [ -n "$VISUAL" ]; then
"$VISUAL" "$1"
elif [ -n "$EDITOR" ]; then
"$EDITOR" "$1"
else
vi "$1"
fi
}
把它的.bashrc與medit script.sh
叫它它首先會嘗試運行$VISUAL
和$EDITOR
指定的編輯器,並回落到vi
如果有沒有指定標準編輯器。
我會寫這樣的事:
# Usage: just like 'builtin printf'
fatal_error() {
builtin printf "[email protected]" >&2
exit 1
}
# Usage: medit [file] [more arguments]
medit() {
# If we have arguments
if [ $# -gt 0 ]; then
# If $1 file does not exist, or is empty,
# put a shebang line into it. See `help test`.
if [ ! -s "$1" ]; then
printf "%s\n" "#!/bin/bash -" > "$1" || \
fatal_error "Failed to write to %s\n" "$1"
fi
# Make $1 executable
chmod +x "$1" || fatal_error "failed to chmod %s\n" "$1"
fi
# Run the default editor with the arguments passed to this function
"${EDITOR:-${VISUAL:-vi}}" "[email protected]"
}
的medit
命令可以調用就像默認編輯器,即使沒有參數。
在關閉的機會,你不知道如何重新使用上面的腳本,把代碼放到一些~/scripts/medit
和source
從相應的初始化腳本,例如~/.bashrc
:source ~/scripts/medit
。
相當不錯的實現。我看到一個錯誤:它應該創建該文件,只有當它不存在,因爲我們不希望發生意外。其他的評論只是個人喜好,不是定義一個新的效用函數來保存兩行代碼,而是一個首選項。 – sorin
@sorin,增加了一個'[! -s「$ 1」]'測試 –
你要求的是一個別名。
如果不使用一個或多個功能,就沒有辦法完成所有要求。
但有一種方法,使一個別名定義一些功能,也稱他們爲:
alias medit='
SayError(){ local a=$1; shift; printf "%s\n" "$0: [email protected]" >&2; exit "$a"; }
medit(){
[[ $# -lt 1 ]] &&
SayError 1 "We need at least the name of the file as an argument"
[[ ! -s $1 ]] && echo "#!/bin/bash" > "$1" ||
SayError 2 "File $1 already exists"
chmod u+x "$1" ||
SayError 3 "File $1 could not be made executable"
${VISUAL:-${EDITOR:-emacs}} "$1" ||
SayError 4 "File $1 could not be open in the editor"
}
\medit'
您需要執行別名medit
的上述定義或將其放置在~/.bashrc
,或者乾脆採購它在運行外殼,使其存在。
然後,當別名被調用時,它定義了兩個函數:SayError
和medit
。
是的,與別名具有相同名稱的函數:medit
。
函數定義後,別名將使用一招調用該函數:
\medit
由於(嚴格地說)一\medit
是不完全的別名medit
,Bash保留搜索和發現功能medit
,到那時已被定義並執行。
當然,您可以定義函數並使用它們而不必使用別名來定義函數,這是您的選擇。
有什麼不錯的是有選擇的。 :)
這是你能如何定義所有的源文件:
alias medit='\medit'
SayError(){ local a=$1; shift; printf "%s\n" "$0: [email protected]" >&2; exit "$a"; }
medit(){
[[ $# -lt 1 ]] &&
SayError 1 "We need at least the name of the file as an argument"
[[ ! -s $1 ]] && echo "#!/bin/bash" > "$1" ||
SayError 2 "File $1 already exists"
chmod u+x "$1" ||
SayError 3 "File $1 could not be made executable"
${VISUAL:-${EDITOR:-emacs}} "$1" ||
SayError 4 "File $1 could not be open in the editor"
}
我想'測試-f'創建一個新的文件之前。 –