Help us understand the problem. What is going on with this article?

コマンドが存在するかしないかを判定して, 条件分岐する構文のまとめ

Vim

executable()関数を使う.

~/.vimrc
" コマンドが存在すれば
if executable('git')
    NeoBundle 'mattn/gist-vim'
endif

Emacs

executable-find関数を使う.

~/.emacs
(when (executable-find "terraform") ; コマンドが存在すれば
  (el-get-bundle terraform-mode)
  )

sh

hashtype, which, command -vなどを使う.

ワンライナー

type htop > /dev/null 2>&1 && echo Success!
# コマンドが存在すれば
type htop > /dev/null 2>&1 || echo Error!
# コマンドが存在しなければ

複数行

type htop > /dev/null 2>&1
if [ $? -eq 0 ] ; then # コマンドが存在すれば
    echo Success!
    alias top=htop
else                   # コマンドが存在しなければ
    echo Error! >&2
    exit 1
fi

簡潔に書くと:

if type htop > /dev/null 2>&1; then # コマンドが存在すれば
    echo Success!
    alias top=htop
else                                 # コマンドが存在しなければ
    echo Error! >&2
    exit 1
fi

PowerShell

ワンライナー

&&||に対応するものはたぶんない ?

複数行

Get-Command (gcm) コマンドレットを使う.

gcm perldoc -ea SilentlyContinue | Out-Null
if ($? -eq $true) { # コマンドが存在すれば
    Write-Output 'Success!'
    perldoc perldoc
} else {            # コマンドが存在しなければ
    Write-Error 'Error!'
    exit 1
}

簡潔に書くと:

if (gcm perldoc -ea SilentlyContinue) { # コマンドが存在すれば
    Write-Output 'Success!'
    perldoc perldoc
} else {                                # コマンドが存在しなければ
    Write-Error 'Error!'
    exit 1
}

コマンドプロンプト

WHEREコマンドを使う.

ワンライナー

WHERE /Q perldoc && ECHO Success!
REM コマンドが存在すれば
WHERE /Q perldoc || ECHO Error!
REM コマンドが存在しなければ

複数行

WHERE /Q perldoc
IF %ERRORLEVEL% == 0 ( :: コマンドが存在すれば
    ECHO Success!
    perldoc perldoc
) ELSE (               :: コマンドが存在しなければ
    ECHO Error! >&2
    EXIT /B 1
)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away