在bash脚本中,我如何拥有一个变量,该变量接受用户输入不超过300个字符,并以用户类型显示剩馀字符数?
在这种情况下,字符将是与get的提要相对应的数字,在一个块中最多有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
};发布于 2014-01-25 10:09:19
因为我理解这个问题。它与输入提示符有关,输入提示符将在输入数字时动态更新。
这是一个解决方案,是基于对一个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那样正确处理游标移动转义字符。但它可能会让你走上正轨。
发布于 2014-01-24 17:38:28
如果有一个由空格分隔的单词组成的字符串,您可以这样对它进行迭代:
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}"
donehttps://stackoverflow.com/questions/21338070
复制相似问题