簡體   English   中英

bash中變量的空格和花括號

[英]Spaces and curly braces for variables in bash

有沒有辦法使${VAR}像用雙引號引起來一樣擴展?

那不是我想要看到的:

% A="some spaces in there"
% touch ${A}
% ls -1
in
some
spaces
there

當然,我可以使用"$VAR"類的典型符號。 但這在帶引號的文本等中使用引號時比較麻煩。我想知道是否存在一種擴展$ {...}表示法的方法,該方法會將${...}視為好像是"${...}"而不會自己使用雙引號?

不遵循公認的最佳實踐 (以及學習shell的實際工作方式)很可能會咬你。 反復。 帶有僵屍病毒感染的fang牙。 一些可以幫助您的事情:

  • 您可以對單個參數的不同部分使用不同的引號,只要起始引號和結束引號彼此相鄰即可:

     $ printf '%q\\n' "foo 'bar' baz"'nuu "boo" zoo' foo\\ \\'bar\\'\\ baznuu\\ \\"boo\\"\\ zoo 
  • 您可以在子外殼中設置IFS以避免搞亂整個腳本:

     $ a="some spaces in there" $ (IFS= && touch ${a}) $ ls -1 some spaces in there 

您可以將IFS變量設置為在Shell拆分變量時忽略空格。 當輸入可能包含空格的輸入時,這也很有用。

$ cat /tmp/t.sh
IFS="$(printf '\n\t')"
A="some spaces in there"
touch ${A}
ls -l
$ /tmp/t.sh
some spaces in there

(如果您的字符串中有*之類的字符,請嘗試使用-f來禁用通配符(請參閱幫助集),謝謝@glenn jackman。但是,實際上,在文件名中添加*會帶來麻煩!)

和原始的:

$ cat /tmp/t.sh
#!/bin/bash
A="some spaces in there"
touch ${A}
ls -1
$ /tmp/t.sh 
in
some
spaces
there
$

暫無
暫無

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

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