Deutsch   English   Français   Italiano  
<20250305103210.358@kylheku.com>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: ...!weretis.net!feeder9.news.weretis.net!news.quux.org!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail
From: Kaz Kylheku <643-408-1753@kylheku.com>
Newsgroups: comp.unix.shell
Subject: Re: (shellcheck) SC2103
Date: Wed, 5 Mar 2025 18:40:30 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 72
Message-ID: <20250305103210.358@kylheku.com>
References: <vq9nto$18ps$1@news.xmission.com>
Injection-Date: Wed, 05 Mar 2025 19:40:31 +0100 (CET)
Injection-Info: dont-email.me; posting-host="e703fbd4fabb26684ed42c07be41654f";
	logging-data="2674094"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX18qxecQ4uBdSaP3l0YMVnsf3icgAmmsZwU="
User-Agent: slrn/pre1.0.4-9 (Linux)
Cancel-Lock: sha1:M9xBHCbMimDSfXC02VrKoilz/b4=
Bytes: 2846

On 2025-03-05, Kenny McCormack <gazelle@shell.xmission.com> wrote:
> All testing done with shellcheck version 0.10.0 and bash under Linux.
>
> Shellcheck says that you should replace code like:
>
>     cd somedir
>     do_something
>     cd ..	# (Or, cd -, which is almost, but not exactly the same thing)
>
> with
>
>     (
>     cd somedir
>     do_something
>     )

That obviously won't work if do_something has to set a variable
that is then visible to the rest of the script.

Forking a process just to preserve a current working directory
is wasteful; we wouldn't do that in a C program, where we might
open the current directory to be saved, and then fchdir back to it.

However, most of the actions in a shell script fork and exec
something anyway.

> The ostensible rationale is that it is shorter/easier to code, but the real
> rationale is that if the cd fails, putting it into a subshell "localizes"
> the damage.

  save_pwd=$(pwd)   # local save_pwd=$(pwd) in shells that have local

  if cd somedir ; then
    ...
    cd "$save_pwd"
  else
    ...
  fi

> but the more general pattern would be:
>
>     cd somewhere;...;cd -

cd - will break if any of the steps in between happen to to cd;
it is hostile toward maintenance of the script.

By the way, we should also try to exploit the capability of commands to
do their own chdir.

E.g:

  save_pwd=$(pwd)
  cd somewhere
  tar czf "$save_pwd"/foo.tar.gz .
  cd "$save_pwd"

becomes

  tar -C somewhere -czf foo.tar.gz .

tar will change to somewhere for the sake of finding the
files, and will resolve the . argument relative to that location,
but the foo.tar.gz file is created in the original directory
where it was invoked.

Another utility with -C <dir> is make.


-- 
TXR Programming Language: http://nongnu.org/txr
Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal
Mastodon: @Kazinator@mstdn.ca