1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

コマンド実行時に先頭の「$」を無視する

Posted at

問題

技術記事のコマンド例をコピペすると、こんな感じで$記号まで含まれていることがよくあります。

$ npm install express
$ git clone https://github.com/...

これをそのままターミナルに貼り付けると...

zsh: command not found: $

イライラしますよね。毎回手動で$を削除するのは面倒です。

解決方法

~/.bashrc~/.zshrcたった3行追加するだけで解決します。

# $ を無視するコマンドを定義
function $ {
    "$@"
}

これで完了です!

仕組み

  • $という名前の関数を定義
  • "$@"で渡された引数(実際に実行したいコマンド)をそのまま実行
  • $ ls -laは実質的にls -laとして実行される

使用例

設定後は、記事からそのままコピペできます:

$ cd ~/projects
$ mkdir new-project
$ git init

すべて正常に実行されます!

適用方法

  1. ~/.bashrc~/.zshrcを編集して上記のコードを追加
  2. 設定を反映:
    source ~/.zshrc
    
    または、ターミナルを再起動

その他の記号にも対応したい場合

#>なども同様に定義できます:

function $ { "$@" }
function \# { "$@" }
function \> { "$@" }

#はコメント記号なので\でエスケープが必要です

注意点

  • 環境変数の$とは別物なので、$HOME$PATHなどには影響しません
  • サブシェルの$(command)にも影響しません
  • 純粋にコマンドの先頭の$だけを処理します

まとめ

わずか3行の設定で、技術記事からのコピペがストレスフリーになります。もう$を手動で削除する必要はありません!

Happy Coding! 🚀

1
1
4

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?