一般ユーザに書き込み権限が無いディレクトリでsudoコマンドを使い、以下のようなコマンドを実行するとエラーになります。
sakura@ubuntu:/var/www$ sudo echo "hello world" > hello.html -bash: hello.txt: 許可がありません
本記事はsudoコマンドでリダイレクトしたり、複数のコマンドをsudoの権限で動作させる方法を記します。
manコマンドでsudoを見ると書いてありました。
以下、man sudoの抜粋です。
To make a usage listing of the directories in the /home partition. Note that this runs the commands in a sub-shell to make the cd and file redirection work. $ sudo sh -c "cd /home ; du -s * | sort -rn > USAGE"
つまり、リダイレクトを可能にするにはsh -cを利用しコマンド群はダブルクォートで囲めば良いわけです。
sudo sh -c "echo 'hello world' > hello.html"
実際に実行した時の出力です。
sakura@ubuntu:~$ cd /var/www/ sakura@ubuntu:/var/www$ sudo sh -c "echo 'hello world' > hello.html" [sudo] password for sakura: sakura@ubuntu:/var/www$ ls hello.html hello.html
つまり、sudoでリダイレクトやsudoで複数コマンドを利用したい場合は、以下のようにすれば動作します。
sudo sh -c "コマンド..."
以上、sudoでリダイレクトや複数コマンドを実行する方法でした。