注意:請對標題進行反饋,老實說我不知道??如何命名這個問題。
我試圖設計一個代碼,每次用戶將檔案放入tools檔案夾中時,它都會自動添加到menu.sh腳本的主代碼中,因此對用戶來說更簡單。
menu.sh 作業正常,但每次用戶添加新腳本時,他都需要在主腳本中添加兩行代碼(menu.sh)
例如,假設用戶想要添加一個名為run-scrape.sh
"run-scrape" need to be added:
-options variable
-added in the source command inside the case statment
我正在嘗試自動化這兩個任務,以便對用戶來說更簡單。
我愿意采用不同的方法來執行此操作或鏈接到類似的東西,但我找不到類似的東西。
背景:
檔案夾結構:
~
scripts
menu.sh, tools
> cd tools
pushing-code.sh, purge-data.sh, run-scrape.sh
選單.sh:
title="title"
prompt="Pick an option(number): "
options=(
"pushing code" \
"purge-data" \
"run-scrape" \
)
echo "$title"
PS3="$prompt"
select opt in "${options[@]}" "Quit"; do
case "$REPLY" in
0) source $(pwd)/scripts/tools/pushing-code.sh; my_func;;
0) source $(pwd)/scripts/tools/purge-data.sh; my_func;;
0) source $(pwd)/scripts/tools/run-scrape.sh; my_func;;
$((${#options[@]} 1))) echo "Goodbye!"; break;;
*) echo "Invalid option. Try another one.";continue;;
esac
解決方案:
基本上一些如何需要在 menu.sh 代碼中創建這兩個組件:
變數:選項
myFileNames=$(ls ~/$(pwd)/scripts/tools) for file in $myFileNames;
除了檔案名之外的每個檔案的 case 陳述句下面的代碼行都是相同的,在這個例子中:push-code.sh因此將其添加到 menu.sh 代碼中:
#sample: 0) source $(pwd)/scripts/tools/pushing-code.sh; my_func; path=$(pwd) args=() for i in myFileNames; do args=("0) source $path/scripts/tools/$i ; my_func;") done select opt in "${options[@]}" "Quit"; do case "$REPLY" in args $((${#options[@]} 1))) echo "Goodbye!"; break;; *) echo "Invalid option. Try another one.";continue;; esac
我認為它沒有很好地組合在一起,過去有沒有人做過類似的事情來分享代碼:)
uj5u.com熱心網友回復:
1:變數:選項
myFileNames=$(ls ~/$(pwd)/scripts/tools) for file in $myFileNames;
- 使用路徑名擴展(通配符),而不是
ls. - 并使用它來填充陣列,而不是扁平字串。還
~/$(pwd)/scripts/tools沒有意義。- 如果您想假設作業目錄包含
scripts/一個子目錄,那么只需使用相對路徑 (scripts/tools)。 - 如果要提供相對于主目錄的路徑,請使用
~/literal/path/to/scripts/tools - 如果您想要相對于腳本位置的路徑,請參閱如何從腳本本身中獲取 Bash 腳本所在的目錄?
- 如果您想假設作業目錄包含
總的來說,這些方面的東西
# Create an array of all the *.sh files in the tools directory
options=(/path/to/tools/*.sh)
例如,您可以通過以下方式檢查結果
echo "${options[@]}"
2:case陳述句下面的代碼行對于除了檔案名之外的每個檔案都是相同的,在這個例子中:push-code.sh
擁有陣列中的選項,您可以通過其索引訪問每個選項。這與 using 很好地配對select,類似于以下內容:
# Select from among elements of the options array
select choice in "${options[@]}"; do
if [[ -n "$choice" ]]; then
# read and evaluate the commands from the selected file
# select options are numbered from 1, but array indices from 0
source "${options[$((choice - 1))]}"
break
else
echo "$REPLY" is not a valid selection
# ...
fi
done
該select命令將自動回圈,直到break執行命令或在標準輸入上達到 EOF。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532830.html
標籤:重击自动化嘘
