Lock in $30 Savings on PRO—Offer Ends Soon! ⏳

ShellCheckでShellScriptを少しまともに

 ShellCheckでShellScriptを少しまともに

Kenichiro MATOHARA

April 25, 2021
Tweet

More Decks by Kenichiro MATOHARA

Other Decks in Technology

Transcript

  1. ShellCheckでshell scriptをまともに ShellCheckでshell scriptをまともに する する via ,. /-| (--;

    (,-'; _/_.-'; _/-.__._< .-'`-.__ '\ .'`---=___`===': /_..---' ___.--.' |` ___.--' __ .i| |-' ___.--'_.8:E| \,-' __.-/88::E! `-.,' _.'|88::E| `;'../88:: E; |.'!88::E"/ /.''!"iiE / `--'`._.-' hjw https://ascii.co.uk/art/shell 5 / 21
  2. コマンドライン コマンドライン $ shellcheck ./sample.sh In ./sample.sh line 3: for

    f in $(ls *.m3u) ^---------^ SC2045: Iterating over ls output is fragile. Use globs. ^-- SC2035: Use ./*glob* or -- *glob* so names with dashes won't become In ./sample.sh line 5: grep -qi hq.*mp3 $f \ ^-----^ SC2062: Quote the grep pattern so the shell won't interpret it. ^-- SC2086: Double quote to prevent globbing and word splitting. Did you mean: grep -qi hq.*mp3 "$f" \ In ./sample.sh line 6: && echo -e 'Playlist $f contains a HQ file in mp3 format' ^-- SC2039: In POSIX sh, echo flags are undefined. ^ SC2016 E i d 't d i i l t d bl t 9 / 21
  3. ShellCheckを参考に書き換え ShellCheckを参考に書き換え ↓ 警告と修正例が便利 Wikiで詳細が確認できる #!/bin/sh ## Example: a typical

    script with several problems for f in $(ls *.m3u) do grep -qi hq.*mp3 $f \ && echo -e 'Playlist $f contains a HQ file in mp3 format' done #!/bin/sh ## Example: a typical script with several problems for f in *.m3u do [ -e "$f" ] || break grep -qi "hq.*mp3" "$f" \ && echo "Playlist $f contains a HQ file in mp3 format" done 11 / 21
  4. ShellCheckのチェックシェル変更 ShellCheckのチェックシェル変更 man 1 shellcheck -s <SHELL> でチェックする shell を指定できる

    既定値は bash -s shell, –shell=shell Specify Bourne shell dialect. Valid values are sh, bash, dash and ksh. The default is to use the file's shebang, or bash if the target shell can't be determined. 14 / 21
  5. その他 その他 Debian devscripts パッケージに checkbashisms というscriptも (未確認) $ sudo

    apt install devscripts $ checkbashisms -f slide/resources/sample.sh possible bashism in slide/resources/sample.sh line 6 (echo -e): grep -qi hq.*mp3 $f \ && echo -e 'Playlist $f contains a HQ file in mp3 format' 15 / 21
  6. vim vim itspriddle/vim-shellcheck: Vim wrapper for ShellCheck, a static analysis

    tool for shell scripts. $ mkdir -p ~/.vim/pack/shellcheck/start $ cd ~/.vim/pack/shellcheck/start $ git clone https://github.com/itspriddle/vim-shellcheck.git $ vim -u NONE -c "helptags vim-shellcheck/doc" -c q 17 / 21
  7. 奥付 奥付 発表 2021-04-25(Sun) 発表者 公開URL , , 利用ソフトウェア ライセンス

    CC BY-NC-SA 4.0 鹿児島Linux勉強会 2021.04(オンライン開催) Kenichiro Matohara(matoken) SpeakerDeck pdf pdf-sig source Asciidoctor Reveal.js 21 / 21