Steps to create and execute the bash script
Step 1: Create Script File
Open the terminal window using the keyboard shortcut “Ctrl + Alt + T“. Using any text editor like vim, vi, or nano, open a new blank file in the text editor.
vim web_server.sh
Step 2: Write Script Code
Once the file is been created, write the below script code into the file.
# Replace "localhost" and "80" with your target host and port
host="localhost"
port="80"
# Check if the web server is running
if nc -zv $host $port 2>&1 | grep -q "succeeded"; then
echo "Web server is running on $host:$port"
else
echo "Web server is not running on $host:$port"
fi
Step 3: Make the Script Executable
Use the chmod command to make the script executable. This command grants execute permission to the script.
chmod +x web_server.sh
Step 4: Run the Script
Execute the script by typing by executing the below command. Command runs the script and displays the output in the terminal.
./web_server.sh
Output:
The script will check if a web server is running on localhost at Port 80. The script will print a message indicating whether the web server is running or not based on the success or failure of the connection attempt.
Run a Command Conditionally with netcat and grep
In this article, we will explore the combination of Netcat (nc) and Grep commands in a Unix-like environment to execute commands conditionally based on specific search criteria. Netcat enables network communication, serving as a tool for sending and receiving data across networks. Meanwhile, Grep excels at pattern matching within textual data. By integrating these commands, users can efficiently filter and process network data, running commands selectively based on the results of pattern matching. This article explores a script demonstrating the process to run a command conditionally with netcat and grep.