Ром*_*ман 1 linux bash shell sh
我需要在行首打印带有一些空格的单词,并且我需要使用变量设置空格计数。
此代码不起作用:
spaces=20
echo "spaces: $spaces"
for ((n=0;n<$spaces;n++))
do
printf '%s' ''
done
printf '%s' 'hello!'
Run Code Online (Sandbox Code Playgroud)
实际输出:
spaces: 20
hello!
Run Code Online (Sandbox Code Playgroud)
预期输出:
spaces: 20
hello!
Run Code Online (Sandbox Code Playgroud)
您可以只使用 singleprintf
来获得所需的空格填充数:
printf '%*s\n' "$spaces" 'hello!'
Run Code Online (Sandbox Code Playgroud)
hello!
Run Code Online (Sandbox Code Playgroud)