This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
##Read file extension and add shenbang to file. | |
file=$1 | |
if [ $# -ne 1 ]; then | |
echo "Usage: $0 [filename]" | |
exit 1 | |
fi | |
#Get file extension | |
ext=$(ls $file | egrep "\." | sed 's/^[a-z,A-Z,0-9,_,/]*//g') | |
case "$ext" in | |
\.sh) | |
sed -i '' -e '1i\ | |
#!/bin/sh | |
' $file | |
;; | |
\.py) | |
sed -i '' -e '1i\ | |
#!/usr/bin/python | |
' $file | |
;; | |
\.rb) | |
sed -i '' -e '1i\ | |
#!/usr/bin/ruby | |
' $file | |
;; | |
\.pl) | |
sed -i '' -e '1i\ | |
#!/usr/bin/perl | |
' $file | |
;; | |
*) | |
echo "Unknown file type: $file" | |
esac |
ファイル名の拡張子に応じて、ファイルの行頭に適切なシバンを挿入するスクリプトです。
メモ
sedコマンドで i オプションを指定すると出力結果をファイルに上書き保存できる
以上
2015年9月23日 追記
Mac OS-X でも動作するように修正しました。 CentOS 6.6でも(エラーメッセージは出ますが、)ちゃんと動作します。
引数に複数ファイルを指定できるようにしました。また引数に「*.sh」などと指定すればディレクトリ内の全てのsh拡張子ファイルの書き換えができます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
## This script will read the file extension and add proper shenbang to the script | |
# Exit if no args | |
if [ $# -eq 0 ]; then | |
echo "Usage: $0 [filename]" | |
exit 1 | |
fi | |
for file in $@ | |
do | |
# Exit if file does not exist | |
if [ ! -f $file ]; then | |
echo "file does not exist" | |
exit 2 | |
fi | |
# Get file extension | |
ext=$(echo "$file" | rev | cut -c 1-3 | rev) | |
# Delete old shenbang and add new one. Exit if file type is unknown | |
case "$ext" in | |
\.sh) | |
sed -i '' -e '/^#!/d' $file; sed -i '' -e '1i\ | |
\#!/bin/bash | |
' $file | |
;; | |
\.py) | |
sed -i '' -e '/^#!/d' $file; sed -i '' -e '1i\ | |
\#!/usr/bin/python | |
' $file | |
;; | |
\.rb) | |
sed -i '' -e '/^#!/d' $file; sed -i '' -e '1i\ | |
\#!/usr/bin/ruby | |
' $file | |
;; | |
\.pl) | |
sed -i '' -e '/^#!/d' $file; sed -i '' -e '1i\ | |
\#!/usr/bin/perl | |
' $file | |
;; | |
*) | |
echo "Unknown file type: $file" | |
exit 3 | |
esac | |
echo "$file: complete!" | |
done |
以上