4
3

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 5 years have passed since last update.

Linux & bashで自作コマンドを作成する

4
Posted at

環境

UbuntuとRaspbianで確認した.

ubuntuの環境
$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 18.04.3 LTS
Release:	18.04
Codename:	bionic
raspbianの環境
$ lsb_release -a
No LSB modules are available.
Distributor ID:	Raspbian
Description:	Raspbian GNU/Linux 10 (buster)
Release:	10
Codename:	buster

結論

/usr/local/binにスクリプトを追加するか,aliasとして追加する方法がある.

方法

ここでは,/home/user/applications/my-command.pyを実行するコマンドmy-commandを例とする.

/usr/local/bin

  1. /usr/local/binに以下のソースファイルmy-commandを追加する.

    /usr/local/bin/my-command
    python3 /home/user/applications/my-command.py
    

    /usr/local/binにファイルを追加する際は,rootの権限が必要になる.なお,/usr/binなど,他のdirectoryに追加する方法もあるが,Linuxにおいて,自作プログラムは/usr/local/binに追加するように設計されている1ため,/usr/local/binに追加することを推奨する.

aliasを追加する

  1. ~/.bash_aliasesに以下のソースコードを追記する.

    ~/.bash_aliases
    alias my-command='python3 /home/user/applications/my-command.py'
    

    このとき,=の前後に空白がないように注意すること.

  2. ~/.bashrcを読み込む.

    read_bashrc
    source ~/.bashrc
    

最後に

シェルでmy-commandを実行し,/home/user/applications/my-command.pyが実行されれば,成功である.

両者の違いは何か

/usr/local/binの特徴

  • 自作アプリを作成した際,ソースファイルのコピーと削除のみで,アプリのインストールとアンインストールを容易に自動化することができる.
  • 他のuserも利用できる.

aliasへの追加の特徴

  • User Directoryの中にあるため,rootの権限が不要である.
  • 自作アプリのインストールとアンインストールの際,ファイルの編集を行わなければならないため,多少複雑である.また,これを自動化する際,sedコマンドを利用すれば良いが,パスの指定の際,/が特殊文字であることから,代わりに\/を使用しなければならならず,これの変換が多少複雑である.
  • 他のuserは利用できない.
  1. Learn Linux Shell Scripting – Fundamentals of Bash 4.4: A comprehensive guide to automating administrative tasks with the Bash shell (English Edition) ↩

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?