我正在exec_all_dirsbashrc 中構建一個通用函式,該函式將在多個目錄中運行一個命令。
function exec_all_dirs() {
curdir=$PWD
dirs=(
~/dir1
~/dir2
~/dir3
)
for dir in ${dirs[@]};
do
echo "---------- $dir ---------"
"$@" # run the command here.
done
cd $curdir
}
function all_func() {
exec_all_dirs 'cd $dir && another_func_defined_in_bashrc' # how to pass $dir
}
function all_du() {
exec_all_dirs 'du -sh $dir'
}
如何$dir作為引數傳遞給以使其exec_all_dirs在 for 回圈中得到擴展?
uj5u.com熱心網友回復:
相反,請考慮采用更安全、更易于使用的不同方法。像作業一樣xargs作業。允許將命令(按原樣由單詞分隔)傳遞給您的命令。然后在單獨的函式中定義作業。這樣你就不必處理把它全部放在單引號中。將變數背景關系"$dir"作為位置引數傳遞給命令。
exec_all_dirs() {
local curdir dirs
curdir=$PWD
dirs=(
~/dir1
~/dir2
~/dir3
)
for dir in "${dirs[@]}"; do
echo "---------- $dir ---------"
"$@" "$dir"
done
cd $curdir
}
_all_func_in() {
if cd "$1"; then
another_func_defined_in_bashrc
fi
}
all_func() {
exec_all_dirs _all_func_in
}
all_du() {
exec_all_dirs du -sh
}
使用 shellcheck 檢查您的腳本。不要使用function name()-只是name()。
如何將 $dir 作為引數傳遞給 exec_all_dirs 以便它在 for 回圈中得到擴展?
您可以自行更換:
echo "$1" | sed 's/$dir/'"$dir"'/g'
你可以運行eval:
eval "$@"
uj5u.com熱心網友回復:
像這樣嘗試:
exec_all_dirs(){
local curdir=$PDW
local cmd dir
local dirs=(
~/dir1
~/dir2
~/dir3
)
for dir in ${dirs[@]}; do
echo "---------- $dir ---------"
printf -v cmd "$1" "$dir"
bash -c "$cmd"
done
cd $curdir
}
all_fu(){ exec_all_dirs 'cd %s && another_func_defined_in_bashrc'; }
all_du(){ exec_all_dirs 'du -sh %s'; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341204.html
