我怎样才能在bash脚本中有一个变量,用户输入的字符数不超过300个,并显示用户输入的剩余字符数?
在这种情况下,字符将是与来自get-iplayer的提要相对应的数字,块中最多4个字符与空格分隔。
相关脚本如下 -
{
read -n1 -p "Do you want to download some tv programmes? [y/n/q] " ynq ;
case "$ynq" in
[Yy]) echo
read -n300 -p "Please input the tv programme numbers to download [max 300 characters] " 'tvbox'
echo
cd /media/$USER/back2/proggies/
/usr/bin/get-iplayer --get $tvbox
;;
[Nn]) echo;; # moves on to next question in the script
[Qq]) echo; exit;; # quits
* ) echo "Thank you ";;
esac
};
答案 0 :(得分:1)
如果你有一个由空格分隔的单词组成的字符串,你可以像这样迭代它:
str="hello world nice to meet you"
for word in $str; do
echo "word=$word"
done
另一方面,如果get-iplayer --get
需要一个由空格分隔的单词组成的字符串的参数,则需要引用变量:
/usr/bin/get-iplayer --get "$tvbox"
我从您的评论中假设您输入“123 456 789 234 567 890 345”,您需要调用以下程序:
/usr/bin/get-iplayer --get "123 456 789 234"
/usr/bin/get-iplayer --get "567 890 345"
如果那是真的:
printf "%s\n" $tbbox | paste - - - - | while read four; do
/usr/bin/get-iplayer --get "$four"
done
或
nums=( $tvbox ) # this is now an array
for ((i=0; i < ${#nums[@]}; i+=4)); do
/usr/bin/get-iplayer --get "${nums[@]:$i:4}"
done
答案 1 :(得分:1)
据我了解这个问题。它是关于输入提示,将在输入数字时动态更新。
这是一个解决方案,它基于对answer的一个小修改,大约两年前发布在本网站上的另一个问题。
将以stty cbreak
模式读取每个字符的脚本转换为名为$result
的变量,并相应地更新提示。
#!/bin/bash
# Input a line with a dynamically updated prompt
# and print it out
ask () {
n=$1 # the limit on the input length (<1000)
if [ -z "$2" ] ; then # the name of variable to hold the input
echo "Usage $0: <number> <name>";
return 2;
fi
result="" # temporary variable to hold the partial input
while $(true); do
printf '[%03d]> %s' "$n" "$result"
stty cbreak
REPLY=$(dd if=/dev/tty bs=1 count=1 2> /dev/null)
stty -cbreak
test "$REPLY" == "$(printf '\n')" && {
printf "\n"
eval "$2=$result"
return 0
}
test "$REPLY" == "$(printf '\177')" && {
# On my terminal 0x7F is the erase character
result=${result:0:-1}
(( n = $n + 1 ))
printf "\r\033[K"
continue
}
result="${result}$REPLY"
(( n = $n - 1 ))
if [ $n -eq 0 ] ; then
printf "\n"
eval "$2=$result"
return 1
fi
printf "\r\033[K" # to clear the line
done
}
echo "Please input the tv programme numbers to download [max 300 characters]"
ask 300 'tvbox'
echo "$tvbox"
# ... here goes the code to fetch the files ...
这个脚本被烘焙了一半,因为它不像read
那样正确处理光标移动转义字符。但它可能会让你走上正轨。