- Bash Cookbook
- Ron Brash Ganesh Naik
- 287字
- 2021-07-23 19:17:32
Redirection and pipe bonzanza
Open a shell and create a new bash file in your favorite editor:
#!/bin/sh
# Let's run a command and send all of the output to /dev/null
echo "No output?"
ls ~/fakefile.txt > /dev/null 2>&1
# Retrieve output from a piped command
echo "part 1"
HISTORY_TEXT=`cat ~/.bashrc | grep HIST`
echo "${HISTORY_TEXT}"
# Output the results to history.config
echo "part 2"
echo "${HISTORY_TEXT}" > "history.config"
# Re-direct history.config as input to the cat command
cat < history.config
# Append a string to history.config
echo "MY_VAR=1" >> history.config
echo "part 3 - using Tee"
# Neato.txt will contain the same information as the console
ls -la ~/fakefile.txt ~/ 2>&1 | tee neato.txt
First, ls is a way of producing an error and, instead of pushing erroneous output to the console, it is instead redirected to a special device in Linux called /dev/null. /dev/null is particularly useful as it is a dump for any input that will not be used again. Then, we combine the cat command with grep to find any lines of text with a pipe and use a fork to capture the output to a variable (HISTORY_TEXT).
Then, we echo the contents of HISTORY_TEXT to a file (history.config) using a stdout redirect. Using the history.configfile, we redirect cat to use the raw file—this will be displayed on the console.
Using a double >>, we append an arbitrary string to the history.config file.
Finally, we end the script with redirection for both stdout and stderr, a pipe,, and the tee command. The tee command is useful because it can be used to display content even if it has been redirected to a file (as we just demonstrated).
- 在最好的年紀(jì)學(xué)Python:小學(xué)生趣味編程
- ReSharper Essentials
- Microsoft Dynamics 365 Extensions Cookbook
- Cocos2d-x學(xué)習(xí)筆記:完全掌握Lua API與游戲項(xiàng)目開發(fā) (未來書庫)
- Hands-On Automation Testing with Java for Beginners
- Learning OpenStack Networking(Neutron)(Second Edition)
- 好好學(xué)Java:從零基礎(chǔ)到項(xiàng)目實(shí)戰(zhàn)
- Applied Deep Learning with Python
- Drupal Search Engine Optimization
- Mastering Bootstrap 4
- PHP 7 Programming Blueprints
- Build Your Own PaaS with Docker
- 快速搞定Spring Boot+Vue全棧開發(fā)
- 區(qū)塊鏈技術(shù)與智能服務(wù)應(yīng)用
- Building Probabilistic Graphical Models with Python