0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[shell]ループ文でシングルクォートの中にダブルクォートやシングルクォートがネストになっている文字列に変数を埋め込む方法

Last updated at Posted at 2022-12-03

やりたいこと

以下のループ文でシングルクォートの中にダブルクォートやシングルクォートがネストになっている文字列の$iを正しく動くようにしたい

test.sh(失敗)
for ((i=0 ; $i < 3 ; i++))
do
echo 'シングルクォートのネストのテスト。\'\""${i}"\"\''
done

このままだと1つ目の\'のエスケープがなかったこと(文字列\'扱い)にされて、以下のエラーが発生する。

エラー文
test.sh: line 3: unexpected EOF while looking for matching `''
test.sh: line 5: syntax error: unexpected end of file

解決方法

シングルクオートを切り離して文字列結合する。('を一つの文字列とみなす)

test.sh(成功)
for ((i=0 ; $i < 3 ; i++))
do

# 以下のように書くことで成功します。ちなみにエスケープをしないとシングルクォートが通常の働きをしてしまうので注意です。
TMPVAR=シングルクォートのネストのテスト。\'\""${i}"\"\'
VAR=\'${TMPVAR}\' 

echo $VAR
done
出力結果
'シングルクォートのネストのテスト。'"0"''
'シングルクォートのネストのテスト。'"1"''
'シングルクォートのネストのテスト。'"2"''

余談

筆者は上記はcurlコマンドをshellで作るときに使用しました。

上記の経緯はthirdパーティのnodeのapiがバグのような挙動を起こしていたためcurlによるapiに選択し直したというものでした。
そしてループ文を使ってコマンドを準備するときに苦労した部分が今回の内容だったので備忘録として残しました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?