Bash filesystem

From wikinotes
Revision as of 20:47, 8 November 2018 by Will (talk | contribs) (→‎path components)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

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
done

by line

while read line; do
   echo "$line"
done < ~/.bashrc