Skip to content
GitLab
Explore
Sign in
Register
Primary navigation
Search or go to…
Project
B
blog
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
nimrod
blog
Commits
b8b27aac
Commit
b8b27aac
authored
9 years ago
by
nimrod
Browse files
Options
Downloads
Patches
Plain Diff
New post on finding if a shell script is sourced or run.
parent
285e185f
No related branches found
No related tags found
No related merge requests found
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
content/sourced_or_not.rst
+32
-0
32 additions, 0 deletions
content/sourced_or_not.rst
with
32 additions
and
0 deletions
content/sourced_or_not.rst
0 → 100644
+
32
−
0
View file @
b8b27aac
Finding is a script sourced or not?
###################################
:date: 2016-02-29
:summary: How to find if a shell script is sourced or not.
I've recently written a shell script that contained several functions and I
wanted to support 2 usage methods. The first is quite regular, marking it as an
executable and running it. The second is to source the script and gain the
functions declared. The problem is not actually performing any tasks (or
outputing anything) if the script is being sourced. It took a bit of fiddling
but I found a short one-liner to add at the top of the script that solves this
in a POSIX-comliant way (at least on my test machines, Debian with Bash and Dash
and KSH on OpenBSD). Here is an example usage:
.. code:: shell
#!/bin/sh -e
# Check if the script is being sourced or not.
[ "$_" != "$0" ] && expr "$-" : ".*i.*" > /dev/null && sourced=1
if [ "$sourced" ]
then
echo Sourced
else
echo Run
fi
The solution is using 2 heuristics. If the last argument (:code:`$_`) if
different from the command name (must be first command run, otherwise the last
argument will be overwritten). The second is if the option flags (:code:`$-`)
contain :code:`i` for interactive. This works when both marking the script as
executable and passing the name as a parameter to the shell.
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment