LoginSignup
7
4

More than 3 years have passed since last update.

シェルスクリプト set コマンド 3つの使用法

Posted at

set コマンドはその実行の仕方によって、全く異なる用途に使われます。

1. オプションフラグをセットする

set コマンドでセットできるオプションフラグはいくつかあります。

help-set
    Options:
      -a  Mark variables which are modified or created for export.
      -b  Notify of job termination immediately.
      -e  Exit immediately if a command exits with a non-zero status.
      -f  Disable file name generation (globbing).
      -h  Remember the location of commands as they are looked up.
      -k  All assignment arguments are placed in the environment for a
          command, not just those that precede the command name.
      -m  Job control is enabled.
      -n  Read commands but do not execute them.
        (一部抜粋)

たとえば、-f を使用してみます。
通常、echo * を実行すると、カレントディレクトリにあるファイル名に展開されますが、set -f を実行することで展開させないことができます。

set-optionf
$ echo *
Documents Downloads metastore_db Music Pictures Public Templates Videos
$ set -f  # パス名の展開を無効にする
$ echo *
*
$ set +f  # パス名の展開を有効にする
$ echo *
Documents Downloads metastore_db Music Pictures Public Templates Videos

2. 位置パラメータをセットする

pos-parameter
# オプションなしで set コマンドに引数を与えると、それらは位置パラメータになる
$ set a b c
echo $2
b

# シェル変数を位置パラメータにセットしたい場合 set -- を使う
$ greet=hello
$ set -- $greet
$ echo $1
hello

# オプション(-a など)を位置パラメータにセットした場合も、set -- を使う
$ set -- -a
$ echo $1
-a

3. シェル変数の一覧を表示する

引数なしで、set コマンド単体で実行すると、シェル変数の一覧が表示されます。

list-shell-variable
$ set
BASH=/bin/bash
BASHOPTS=checkwinsize:cmdhist:complete_fullquote:expand_aliases:extquote:force_fignore:histappend:hostcomplete:interactive_comments:progcomp:promptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
BASH_CMDS=()
BASH_LINENO=()
(一部抜粋)
7
4
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
7
4