अपनी पहली Bash स्क्रिप्ट कैसे लिखें और चलाएँ
Bash स्क्रिप्ट बनाएँ, syntax जाँचें, उसे executable बनाएँ और bash script.sh तथा ./script.sh का अंतर समझें।
इंटरएक्टिव पाठ शुरू करेंBash स्क्रिप्ट एक text file है जिसमें लिखे commands को Bash क्रम से चलाता है। script.sh में shebang और एक command सहेजें, syntax जाँचें, execute permission दें और ./script.sh से चलाएँ। समस्या ढूँढते समय bash script.sh भी उपयोगी है। पहली स्क्रिप्ट की lesson में यही workflow सुरक्षित वातावरण में अभ्यास किया जा सकता है।
Shebang और दिखाई देने वाला command सहेजें
script.sh में ये दो lines लिखें:
#!/usr/bin/env bash
printf '%s\n' 'Hello World'
File को सीधे चलाने पर shebang operating system से कहता है कि वह मौजूदा command search path में bash खोजे। यदि target machine पर Bash निश्चित रूप से वहीं हो तो #!/bin/bash भी सामान्य विकल्प है।
सहेजी गई file देखें:
cat script.sh
इससे खाली file, गलत filename या गलत directory में save होना पता चलता है। Windows से आई file में Unix LF line endings रखें; छिपा हुआ CR सही दिखने वाले shebang पर भी “bad interpreter” दे सकता है।
चलाने से पहले syntax जाँचें
bash -n script.sh
कोई output न आने का अर्थ केवल यह है कि Bash को syntax error नहीं मिला। यह paths, permissions या अपेक्षित परिणाम की पुष्टि नहीं करता।
स्क्रिप्ट को executable बनाएँ
chmod u+x script.sh
Permission जाँचें:
ls -l script.sh
Owner की तीन-character permission में अब x होना चाहिए। chmod file mode बदलता है, file का content नहीं।
चलाने के दो सामान्य तरीके समझें
Current directory से executable file चलाएँ:
./script.sh
./ एक path देता है। अधिकांश shells current directory को अपने आप नहीं खोजते।
या file को स्पष्ट रूप से Bash को दें:
bash script.sh
इस रूप में file readable होनी चाहिए, लेकिन execute bit आवश्यक नहीं है। Bash shebang की परवाह किए बिना content पढ़ता है। इससे read या syntax problem को direct executable launch की problem से अलग किया जा सकता है।
मिले हुए message का निदान करें
- No such file or directory: pwd और ls से location तथा filename जाँचें।
- Permission denied: execute bit, owner, directory permissions और mount options देखें।
- Bad interpreter: shebang path और line endings जाँचें।
- Syntax error: bash -n script.sh चलाकर बताई गई line देखें।
- Unexpected output: हर command को समान inputs के साथ अलग से चलाएँ।
इसके बाद Bash variables, functions या सुरक्षित backup script पढ़ें। GNU Bash shell-script reference script invocation को विस्तार से समझाता है।
संदर्भ
ये दस्तावेज़ लिंक इस लेख में उपयोग किए गए कमांड के लिए आधिकारिक विवरण प्रदान करते हैं।
अगला
ऐसी Bash backup script बनाएँ जो source जाँचे, overwrite रोके, partial archive हटाए और tar file verify करे।