[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: cd as much as possible



Hi Kamaraju.

If I understand this correctly, then this is a kind of traversal - but only for a single directory.

That should be a fairly easy thing to do.

for file in tmp/*; do
  [ -d file ] echo "folder: $file"
done

... only get those names you're interested in ...

for file in tmp/issue-?*; do
  [ -d file ] echo "folder: $file"
done

-d means if file is directory; -f if it's a file, -e if it's "something that exisss"
I use conditional expression instead of 'if' in the above two examples (because I'm lazy).
(details can be found here: <http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression>)

in bash, you can use ${file#pattern}, ${file##pattern}, ${file%pattern} or ${file%%pattern} to grab the first/last part of the pathname

(details on pattern matching can be found here: <http://wiki.bash-hackers.org/syntax/pe#substring_removal> - I tend to like the 'default value' and I've been using 'alternate value' very much)

Example:

for file in tmp/issue-*; do
	if [ -d ]; then
		echo "file  : ${file%/*}"
		echo "  path:file: ${file%/*}"
		echo "  name: ${file##*/}"
		echo "  issue number: ${file##*/issue-}"
	fi
done

bash4 adds some extra powerful string operations, which might be interesting for you, if you know bash4 is always available on the system you're using.

'alternate value' can be useful, when you want to add a few characters if a string is not empty.
Example:
	echo ${string:+, $string}
... will add a preceeding comma if the string is not empty.

Other useful info: <http://wiki.bash-hackers.org/syntax/pattern>


Love
Jens

[Note: Either there's a huge deveral-day-lag, or my postings do not make it to the debian-user list for some reason]

On Thu, 10 Mar 2016 23:00:22 -0500, kamaraju kusumanchi wrote:
> On Thu, Mar 10, 2016 at 1:48 AM, Jens Bauer <jens-lists@gpio.dk> wrote:
>> Hi Kamaraju.
>> 
>> Yes, it's possible. You could for instance write a bash function, 
>> which would do it.
>> But why would you want to do that ?
> 
> I have the following directory structure
> 
> tmp/issue-1
> tmp/issue-5
> tmp/issue-13
> ...
> 
> where the issue numbers are not contiguous. If I am working on an
> issue, say issue-37, I would like to do
> cd tmp/issue-37
> 
> If issue-37 is a new issue, I would like to be inside tmp so I can
> mkdir issue-37 if necessary.
> If it is an existing issue, I would like to be inside issue-37 
> automatically.
> 
>> If you need to create all the directories, then you can just supply 
>> -p to mkdir.
> 
> I am aware of mkdir -p option. But that is not what I want here.
> 
> thanks
> raju
> -- 
> Kamaraju S Kusumanchi | http://raju.shoutwiki.com/wiki/Blog
> 


Reply to: