We’ll delve into a common yet essential task in Shell Scripting: reading from a file and creating it if it doesn’t exist.
Creating a New Script File:
Open a text editor (like nano
or vi
) and create a new file:
Script Content:
Input the following lines into the script:
#!/bin/bash
FILE=input.txt
# Check if the file exists
if [ -f "$FILE" ]; then
echo "Reading from $FILE:"
cat $FILE
else
echo "$FILE does not exist. Creating the file."
touch $FILE
fi
Save and Exit: Save the script and exit the text editor. In nano
, this is done with CTRL+X
, then Y
, and finally Enter
.
Step 3: Making the Script Executable
Change your script’s permissions to make it executable:
chmod +x readfile.sh
Execute the script with:
./readfile.sh