There are many ways to display a text file in a shell script. You can simply use the cat command and display back output on screen. Another option is to read a text file line by line and display back the output. In some cases you may need to store output to a variable and later display back on screen.
Tutorial details | |
---|---|
Difficulty | Easy (rss) |
Root privileges | No |
Requirements | None |
Time | 5m |
Task: Display output using the cat command
Following sample script displays contents of a file called /tmp/input.txt:
#!/bin/bash FILE="/tmp/input.txt" echo "*** File - $FILE contents ***" cat $FILE
Task: Store a file output in a variable
Following sample script displays nameserver IPs:
#!/bin/bash FILE="/etc/resolv.conf" OUT=$(awk '{ print $2 }' $FILE) echo "*** Nameserver IP ***" for ip in $OUT do echo $ip done
Task: Read a text file line-by-line
See our previous tutorial for more information:
- Linux/ UNIX: Read a File Line By Line
- Linux / Unix AWK: Read a Text File
- HowTo: Bash For While Loop Through File Contents Script
- Ksh Read a File Line By Line ( UNIX Scripting )
🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.
🐧 6 comments so far... add one ↓
🐧 6 comments so far... add one ↓
Category | List of Unix and Linux commands |
---|---|
File Management | cat |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Network Utilities | dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time |
Searching | grep • whereis • which |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
2nd option is good. If file is large, one can modify the script a bit to serve the purpose.
How to display certain part of a file? For example, I have a file myFile.Java and I would like to display the contents between lines 30-40. How to do that in linux? with cat?
Thanks,
I have 1 more Que.
i want a shell script for identify mentioned string is file or directory if its a directory then display the contests of the same and if this is file show the content of file
cat $FILE
echo “$(<$FILE)"
tee <$FILE
Sir,
I am a beginner in Linux /Unix and I want answer to the following question.
Q. Write a shell script in Linux /Unix that accepts a text file as input and prints the number of words in the file which have at least one vowel as output.
Sir,
Please give me answer as soon as possible.
Thanks