我如何在bash脚本中具有一个可将用户输入不超过300个字符的变量,并且显示为用户类型剩余的字符数量?
在这种情况下,字符将是对应于Got-iplayer的feed的数字,其中最多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
};
,据我了解这个问题。这是关于输入提示,该提示将在输入数字时动态更新。
这是一个解决方案,基于大约两年前在本网站上发布的另一个问题的答案的小修改。
将一个以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 33[K"
continue
}
result="${result}$REPLY"
(( n = $n - 1 ))
if [ $n -eq 0 ] ; then
printf "n"
eval "$2=$result"
return 1
fi
printf "r 33[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
一样正确处理光标移动逃脱字符。但是它可能会使您步入正轨。
如果您的字符串由空间分离的单词组成,则可以像这样迭代它:
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 "%sn" $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