TweetFollow Us on Twitter

Back to the Shell

Volume Number: 22 (2006)
Issue Number: 9
Column Tag: Mac in the Shell

Back to the Shell

Revisiting the basics in an advanced kind of way.

by Edward Marczak

Introduction

Recently, I've gotten a number of people contacting me asking if I could write some more about "using the shell". Well, for close to two years, that's just about all this column talks about! But, that means it's time for me to get back to basics. For the long-time reader, though, I'll get into some command-line goodness that I haven't tread upon quite yet.

The Shell

When you run Terminal.app, that's your gateway to a shell: the text-based command interpreter. This is similar to a DOS shell or MSH under Windows, an xterm in X, or, a dedicated hardware terminal that is serially patched into a host. This is the original CRT interface into a system (props to punch cards and paper-based teletypes).

Some people also call a GUI interface a "shell". While that's probably partially correct, for the purposes of this column, "shell" will always refer to the text-based, command-line driven variety. Nor will it refer to file manipulation shells like Midnight Commander, et al.

Different shells have arisen over the years, with the Bourne Shell, or "sh" being the original Unix shell. The C-Shell, or "csh", became a popular alternative. Finally, "bash", or, the "Bourne Again Shell" added many features to the original sh, and is now the default shell in OS X (starting with 10.3 - 10.2 and earlier used csh as the default). When I say "default", I mean just that: it's a nice gesture that the OS chooses something for you, but you can choose any shell you like as your default. A user's shell is stored in their user record, either in NetInfo or OpenDirectory.

That's the abridged (re)introduction: A shell is a user interface that accepts input, processes that input, and produces output. For a much deeper introduction, please refer to my March 2005 column in MacTech. (Available now, by the way as part of the MacTech CD - <http://www.mactech.com/cd>).

Father's Day

Father's Day, 2006: Not only am I a father, but I happened to be at my Father's house. Of course, I'm also a consultant, and holidays don't stop clients from calling when there is a problem! So, when I got a "but I'm sure it will only take you a minute" call during the day, I figured I'd make a client happy. But I didn't have my laptop, or any OS X box for that matter. I have to admit that my Father is a Windows guy, so I had access to his machine. There are plenty of ssh clients for Windows (with PuTTY being my favorite <http://www.chiark.greenend.org.uk/~sgtatham/putty/>), and OS X Server has ssh enabled by default. Feel free to enable it in OS X by opening the Sharing Pref Pane and placing a check mark next to "Remote Login". ssh, if you are unfamiliar with it, is the Secure Shell. Now, it's not really a shell in and of itself, but a way to access a remote shell - typically one on another machine. It's 'secure' because all traffic between the ssh client and the ssh server is encrypted. The moral of this tale turns out to be the 'why' section of this article. "Why should I use a text-based interface when I have yummy Aqua?" Let me (briefly) count the ways:

    1. Power: Quickly find and affect a huge number of surgically selected files.

    2. Power: Many times, in many ways, it's the GUI that's still catching up with the shell. There are options in many of the shell tools that just can't be performed with the GUI.

    3. Power: think about the reach that a tool like ssh gives you to access, install, troubleshoot and diagnose remote machines. (I never had to leave my Father's house that day).

Shell Lite

As it turns out, it only did take me a minute with that problem: Windows services just got a little funky on an OS X Server machine. smbd was running, but nmbd had died off. This meant OS X machines could, in tests, access the server using smb://ip.ad.dr.ess, but genuine Windows machines couldn't browse for shares. So, I stopped smb, and started it up again - problem solved. How'd I do that without the GUI-based Server Admin? Easy: the shell-based serveradmin.

I detest opening a console on an OS X Server if it can be avoided. 99% of the time it can be (or close to it. Did you know that 47% of all statistics are made up?). Yes, there are applications that require a GUI session to remain logged in. Thankfully, those are a dying breed. So rather than fire up a resource-heavy GUI, I ssh in and use serveradmin:

# serveradmin stop smb
# serveradmin start smb

As you've probably guessed, the first line has server admin stop Windows services (smb stands for Server Message Block, which is the protocol that Windows uses, and from where SaMBa derives its name). Also note that this is only available on OS X Server. Let's take a closer look:

# serveradmin list
afp
appserver
dhcp
dirserv
dns
filebrowser
ftp
info
ipfilter
jabber
mail
nat
netboot
network
nfs
print
privs
qtss
qtsscontents
signaler
smb
swupdate
vpn
web
webobjects
xgrid
xserve

This displays a list of all services that serveradmin knows how to control. This provides a way to stop, start and get status on each service. Better yet, you can read all of the settings for any particular service. Let's capture our settings for OpenDirectory:

# serveradmin settings dirserv
dirserv:secureConfigRecord:errorValue = 2
dirserv:secureConfigRecord:statusMessage = "Unable to find a computer record for this computer"
dirserv:canKerberize = no
dirserv:LDAPSettings:LDAPDataBasePath = "/var/db/openldap/openldap-data"
dirserv:LDAPSettings:searchTimeout = 3600
dirserv:LDAPSettings:LDAPSearchBase = "dc=radiotope,dc=com"
dirserv:LDAPSettings:LDAPSSLCertificatePath = ""
dirserv:LDAPSettings:LDAPCACertificatePath = ""
dirserv:LDAPSettings:LDAPServerBackend = "bdb"
dirserv:LDAPSettings:useSSL = no
dirserv:LDAPSettings:maxSearchResults = "11000"
dirserv:LDAPSettings:LDAPTimeoutUnits = "seconds"
dirserv:LDAPSettings:LDAPSSLKeyPath = ""
dirserv:masterConfig:replicas:_array_index:0:replicaAddress = "192.168.30.8"
dirserv:masterConfig:replicas:_array_index:0:replicaStatus = "OK"
...
dirserv:replicaLastUpdate = ""
dirserv:masterServer = ""
dirserv:LDAPServerType = "master"
dirserv:MacOSXODPolicy:Configured Security Level:Binding Required = no
dirserv:MacOSXODPolicy:Configured Security Level:Packet Encryption = no
dirserv:MacOSXODPolicy:Configured Security Level:Man In The Middle = no
dirserv:MacOSXODPolicy:Configured Security Level:No ClearText Authentications = yes
dirserv:MacOSXODPolicy:Directory Binding = yes
...
dirserv:kerberizedRealmList:availableRealms:_array_index:0:dirNodePath = "/LDAPv3/127.0.0.1"
dirserv:LDAPDefaultPrefix = "dc=lycaeum,dc=radiotope,dc=com"
...
dirserv:PWPolicyInfo:passwordNotAccount = 1
dirserv:PWPolicyInfo:passwordDisableDate = 0.000000
dirserv:PWPolicyInfo:passwordDisableFailedLogins = 0
We can save all of those settings in a file by redirecting the output:
# serveradmin settings dirserv > od_settings.txt

We can restore those settings by redirecting that saved file back into serveradmin:

# serveradmin settings < od_settings.txt

Nicely, you can gather all settings:

# serveradmin settings all > all_settings.txt

Of course, you can set most of those values, too:

# serveradmin settings afp:guestAccess = yes

The Locked Finder

Ever have the Finder lock up on you? You may still see certain apps running, but you just can't interact with anything. Well, the Finder is just another program running on your system (and one that's severely deprecated since the OS 6/7/8/9 days). If you want to shut down cleanly, you can ssh into the machine in question and issue a shutdown:

# shutdown -h now

The "-h" switch stands for "halt" (power down). You can also reboot the machine with the "-r" switch:

# shutdown -r now

Depending on the state of the machine, 'shutdown' may even hang. But reboot goes to the heart of the matter a little more quickly. Just issue:

# reboot

The box should come down in a hurry and reboot. Sometimes, of course, you just have to accept defeat and understand that a hung box just isn't coming back.

Invisible

Without third-party add-ons, the Finder isn't able to mark a file visible or invisible (or, "hidden"). With Apple's Developer Tools installed, you have access to some utilities that can manipulate Finder-level metadata. Inside /Devloper/Tools, you'll find SetFile and GetFileInfo nestled among many other programs. Use GetFileInfo to peek at a file's current settings:

$ ./GetFileInfo /Users/marczak/Pictures/iChat\ Icons/Flags/UK.gif 
file: "/Library/Application Support/Apple/iChat Icons/Flags/UK.gif"
type: ""
creator: ""
attributes: avbstclinmedz
created: 03/21/2005 00:08:23
modified: 03/21/2005 00:08:23

(note how GetFileInfo properly de-referenced the alias in use here). This should all be pretty self-explanatory with the exception of the 'attributes' line. Each letter represents one attribute; if it's a lower-case letter, that attribute is off, upper-case is on. The attributes are:

    A Alias file

    B Bundle

    C Custom icon (files and folders)

    D Desktop (files and folders)

    E Hidden extension (files and folders)

    I Inited (files and folders)

    M Shared (can run multiple times)

    N No INIT resources

    L Locked

    S System (name locked)

    T Stationery

    V Invisible (files and folders)

    Z Busy (files and folders)

Now, you can use SetFile to change any of those attributes. To make a file hidden to the Finder:

$ /Developer/Tools/SetFile -a V /Users/erm/Applications/Secret.app

...and to bring it back:

$ /Developer/Tools/SetFile -a v /Users/erm/Applications/Secret.app

The behavior for hiding and unhiding has changed somewhere along the line. While the change for both used to be immediate, only hiding is now. Once you use "-a v" - the 'visible' switch, the Finder doesn't pick up the change, and requires a reboot (or, perhaps a log out and log in).

Full Circle

Just to make this complete, I want to follow-up on the 'shell' issue. As I mentioned, you're free to select any shell you like. By default, new accounts in Panther and Tiger (10.3 and 10.4) will setup bash as the default. However, if you've upgraded from 10.2 or earlier, your user record came over intact, and will still retain your setting for C-shell (csh). You can determine which shell you use in a few ways. If you already have a shell open, type 'set'. This displays a list of environment variables. If you're using bash, you'll have some variables defined that start with "BASH". C-Shell defines a 'version' variable. Z-Shell (zsh) defines some variables that start with "ZSH". Perhaps even more definitive would be to run a process status and look for your user name:

$ ps aux | grep marczak | grep sh
marczak    496   0.7 -0.0    27812    736  p7  Ss   Thu03PM   0:01.82 /bin/bash
marczak   3432   0.5 -0.0    27812    364  p7  R+    6:40AM   0:00.00 grep sh
marczak    323   0.0 -0.0    27812    188  p1  S    Thu03PM   0:00.02 -bash
marczak    486   0.0 -0.0    27812    188  p2  Ss+  Thu03PM   0:00.01 /bin/bash
marczak    490   0.0 -0.0    27812    648  p4  Ss+  Thu03PM   0:00.18 /bin/bash
marczak    492   0.0 -0.0    27812    664  p5  Ss+  Thu03PM   0:00.18 /bin/bash
marczak    494   0.0 -0.0    27812    612  p6  Ss+  Thu03PM   0:00.15 /bin/bash

We can check our user record to see what our default is:

$ dscl localhost read /NetInfo/root/Users/marczak | grep -i shell
UserShell: /bin/bash

However, just because we have a default shell doesn't mean we can't override it in some way. You can simply run another shell by typing its name:

Jack-Kerouak:~ marczak$ set | grep BASH

BASH=/bin/bash
BASH_VERSINFO=([0]="2" [1]="05b" [2]="0" [3]="1" [4]="release" [5]="powerpc-apple-darwin8.0")
BASH_VERSION='2.05b.0(1)-release'
Jack-Kerouak:~ marczak$ csh
[Jack-Kerouak:~] marczak% set | grep version
version tcsh 6.12.00 (Astron) 2002-07-23 (powerpc-apple-darwin) options 8b,nls,dl,al,kan,sm,rh,color,
  dspm,filec
[Jack-Kerouak:~] marczak% exit
exit
Jack-Kerouak:~ marczak$

If you're a csh user, you may need to run an installer that depends on bash. That's easy to deal with without changing your login shell. Either type 'bash' to run a bash shell, and then exit it when you're done, or, prepend the command with 'bash'.

The traditional way to change your default shell is to use 'chsh' (change shell) while logged in at a shell. This continues to work in OS X. Running chsh will present you with a vi editor (by default) that lets you update your shell. Save the file, and at next login, you'll see the new shell in action. chsh has been patched on OS X to reach into the appropriate place to update your shell in your user record.

Of course, you're free to update your user record directly using dscl or niutil.

Finally, you can have Terminal.app run any shell (or app) you'd like, despite your default shell settings. Figure 1 shows the Terminal.app preference that lets you choose a shell to run: (top of next column)

The "Execute this command" option can be chosen rather than simply running the default shell from your user record. I use 'screen' as the shell on my personal setup. (See "Screen: Living in A Virtual World", MacTech, September 2005, or, find it on the MacTech CD).



Figure 1: Terminal.app Prefs

Finish

In short, there's no magic. "Using the shell" is just a matter of practice, even for those experienced and familiar with it. Sometimes, "using the shell" involves knowledge of one particular tool, which may run deep. Reading about it only gets you so far, though. Open up Terminal.app (or iTerm, or ssh in from a Linux or Windows box) and start typing! You won't break anything. If you're really paranoid, clone your setup or run on a test system. In any case, getting in an really doing it is what it's all about.

Media of the month! I think this is the first time that I'm going to recommend a Mac-centric title! Amit Singh has released his long awaited "Mac OS X Internals - A Systems Approach". Now, this is not light reading in any sense of the word. The book is 1,600+ pages (physically heavy), and tends toward the deeper, more techy, only-5-people-at-Apple-know-this kind of material. However, you will gain OS X knowledge from this book, even if you do not understand it all! Refer to Amit's profile in last month's MacTech 25 for a little more understanding about his works. In any case, it's highly recommended! Check it out at <http://www.osxbook.com>.

Next month, more shell nuggets. Until then, keep practicing!


Ed Marczak often finds himself living in a shotgun shack, in another part of the world, behind the wheel of a large automobile, in a beautiful house, with a beautiful? wife. After that, it's all about guiding people in their technology endeavors. Find out more at http://www.radiotiope.com

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »
Play Together teams up with Sanrio to br...
I was quite surprised to learn that the massive social network game Play Together had never collaborated with the globally popular Sanrio IP, it seems like the perfect team. Well, this glaring omission has now been rectified, as that instantly... | Read more »
Dark and Darker Mobile gets a new teaser...
Bluehole Studio and KRAFTON have released a new teaser trailer for their upcoming loot extravaganza Dark and Darker Mobile. Alongside this look into the underside of treasure hunting, we have received a few pieces of information about gameplay... | Read more »

Price Scanner via MacPrices.net

14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more
B&H has 16-inch MacBook Pros on sale for...
Apple 16″ MacBook Pros with M3 Pro and M3 Max CPUs are in stock and on sale today for $200-$300 off MSRP at B&H Photo. Their prices are among the lowest currently available for these models. B... Read more
Updated Mac Desktop Price Trackers
Our Apple award-winning Mac desktop price trackers are the best place to look for the lowest prices and latest sales on all the latest computers. Scan our price trackers for the latest information on... Read more
9th-generation iPads on sale for $80 off MSRP...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80 off MSRP on their online store for a limited time. Prices start at only $249. Sale prices for online orders only, in-store prices... Read more
15-inch M3 MacBook Airs on sale for $100 off...
Best Buy has Apple 15″ MacBook Airs with M3 CPUs on sale for $100 off MSRP on their online store. Prices valid for online orders only, in-store prices may vary. Order online and choose free shipping... Read more

Jobs Board

Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Mar 22, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Retail Assistant Manager- *Apple* Blossom Ma...
Retail Assistant Manager- APPLE BLOSSOM MALL Brand: Bath & Body Works Location: Winchester, VA, US Location Type: On-site Job ID: 04225 Job Area: Store: Management Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! In this role, Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now See Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.