LoginSignup
1
1

VScode上でシェルスクリプトのデバッグ方法

Posted at

今回はVScode上でシェルスクリプトのデバッグ方法を紹介します。
rogalmicさんが作ったBash Debugエクステンションを使ってデバッグしていきます。
https://marketplace.visualstudio.com/items?itemName=rogalmic.bash-debug

debugする方法

通常のdebugと同じようにブレークポイントを設定すればそこで止まります。

気を付けること

そのまま実行すると下記のエラーが出る可能性があります。
Error: Only bash versions 4.* or 5.* are supported.
これはエクステンションがbash 4.0 & 5.0しか対応してないからです。

その場合homebrewなどを使ってbash 5.0をインストールして、
launch.jsonでbashのパスを指定します。

"pathBash": "/opt/homebrew/bin/bash",

標準入力

bashからパラメーターを渡すケースが多いと思いますが、
その場合launch.jsonで渡すことができます。

"args": [1]

サンプルlaunch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "bashdb",
            "request": "launch",
            "name": "Bash-Debug (simplest configuration)",
            "pathBash": "/opt/homebrew/bin/bash",
            "program": "${file}",
            "args": [1]
        }
    ]
}

動作確認ようサンプルコード

#!/bin/bash

function is_even() {
  # Check if the input is an even number
  if [ $(($1 % 2)) -eq 0 ]; then
    echo "Even"
  else
    echo "Odd"
  fi
}

input="$1"

if [[ -z "$input" ]]; then
  echo "ERROR: Missing argument"
  echo "Usage: $0 <number>"
  exit 1
fi

if ! [[ $input =~ ^[0-9]+$ ]]; then
  echo "ERROR: '$input' is not a valid number"
  exit 2
fi

result=$(is_even "$input")
echo "The number $input is $result"

出力

The number 1 is Odd
The number 2 is Even
1
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
1
1