簡體   English   中英

UNIX Shell腳本輸出

[英]UNIX Shell Scripting Output

我正在嘗試編寫一個shell腳本“ echo.by”,該腳本可根據用戶選擇多次回顯其參數。 例如,如果用戶輸入命令行

echo.by 5 Play it again, Sam. <return> 

腳本應打印

Play it again, Sam. 
Play it again, Sam. 
Play it again, Sam. 
Play it again, Sam. 
Play it again, Sam. 

但是,我不知道如何只打印山姆,請再次播放並排除第一個參數。 $*命令會打印所有內容,因此我最終得到

5 Play it again, Sam. 
5 Play it again, Sam. 
5 Play it again, Sam. 
5 Play it again, Sam. 
5 Play it again, Sam. 

我的腳本需要能夠容納第一個數字之后的任何腳本,因此我不能僅僅告訴shell回顯$2 $3 $4 $5

這是我的腳本:

count = 0 
while test $count -lt $1 
do 
echo $* 
count = `expr $count + 1` 
done

只需將$1放在一個變量中,您以后將引用它,然后將shift添加到腳本的頂部。

 #!/bin/bash
 times="$1"
 shift
 for f in $(seq "$times"); do
     echo "$@"
 done

編輯 :將$times更改$times小寫,如@Charles Duffy建議。 為了與其他POSIX(-like)系統更好地兼容,您可能需要更改循環以將C樣式for -syntax。 seq命令在NetBSD,FreeBSD和GNU系統中可用。

嘗試使用C樣式的loop 數組slice來執行此操作:

#!/bin/bash

for ((i=0; i<$1; i++)); do
    echo "${@:2:${#@}}"
done
#!/bin/bash
times="$1"
shift
for ((f=0; f<times; i++)); do
    printf '%s\n' "$*"
done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM