Bash filesystem: Difference between revisions
From wikinotes
Line 14: | Line 14: | ||
<blockquote> | <blockquote> | ||
<source lang="bash"> | <source lang="bash"> | ||
basename myfile.mp3 .mp3 #> myfile | basename myfile.mp3 .mp3 #> myfile # strip file-extension from filename | ||
basename /path/to/myfile.mp3 #> myfile.mp3 | basename /path/to/myfile.mp3 #> myfile.mp3 # get filename | ||
dirname /path/to/myfile.mp3 #> /path/to | dirname /path/to/myfile.mp3 #> /path/to # get dirname | ||
filename=$(echo $filename | xargs) | filename=$(echo $filename | xargs) # remove leading/trailing whitespace from variable | ||
[[ "${filepath[1]}" != "/" ]] && filepath="$PWD/$filepath" # abspath-or-relpath to abspath | |||
</source> | </source> | ||
</blockquote><!-- path components --> | </blockquote><!-- path components --> |
Revision as of 12:45, 29 August 2021
checking for files
[ -e ~/.bashrc ] && echo "path exists" [ -f ~/.bashrc ] && echo "file exists" [ -d ~/.vim ] && echo "dir exists" [ -L ~/.bashrc ] && echo "symlink exists"There are many more. See
man test
.
path components
basename myfile.mp3 .mp3 #> myfile # strip file-extension from filename basename /path/to/myfile.mp3 #> myfile.mp3 # get filename dirname /path/to/myfile.mp3 #> /path/to # get dirname filename=$(echo $filename | xargs) # remove leading/trailing whitespace from variable [[ "${filepath[1]}" != "/" ]] && filepath="$PWD/$filepath" # abspath-or-relpath to abspath
writing files
echo 'abc' > /tmp/test.txt # write to /tmp/test.txt (replacing contents if exists) echo 'def' >> /tmp/test.txt # append to /tmp/test.txt
reading files
by word
for word in $(cat "/path/file.txt") ; do echo $word doneby line
while read line; do echo "$line" done < ~/.bashrc